Created
May 17, 2018 00:41
-
-
Save rawiriblundell/4d12efd7f34105ff02f653dfe3f0669b to your computer and use it in GitHub Desktop.
Attempt to replicate 'watch' command, never used, so expelled from my .bashrc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Check if 'watch' is available, if not, enable a stop-gap function | |
| if ! command -v watch &>/dev/null; then | |
| watch() { | |
| local OPTIND colWidth titleHead sleepTime dateNow | |
| while getopts ":hn:vt" optFlags; do | |
| case "${optFlags}" in | |
| (h) printf '%s\n' "Usage:" " watch [-hntv] <command>" "" \ | |
| "Options:" \ | |
| " -h, help. Print a summary of the options" \ | |
| " -n, interval. Seconds to wait between updates" \ | |
| " -v, version. Print the version number" \ | |
| " -t, no title. Turns off showing the header" | |
| return 0;; | |
| (n) sleepTime="${OPTARG}";; | |
| (v) printf '%s\n' "watch. This is a bashrc function knockoff that steps in if the real watch is not found." | |
| return 0;; | |
| (t) titleHead=false;; | |
| (\?) printf '%s\n' "ERROR: This version of watch does not support '-$OPTARG'. Try -h for usage or -v for version info." >&2 | |
| return 1;; | |
| (:) printf '%s\n' "ERROR: Option '-$OPTARG' requires an argument, e.g. '-$OPTARG 5'." >&2 | |
| return 1;; | |
| esac | |
| done | |
| shift $(( OPTIND -1 )) | |
| # Set the default values for Title and Command | |
| sleepTime="${sleepTime:-2}" | |
| titleHead="${titleHead:-true}" | |
| if [[ -z "$*" ]]; then | |
| printf '%s\n' "ERROR: watch needs a command to watch. Please try 'watch -h' for usage information." | |
| return 1 | |
| fi | |
| while true; do | |
| clear | |
| if [[ "${titleHead}" = "true" ]]; then | |
| dateNow=$(date) | |
| (( colWidth = $(tput cols) - ${#dateNow} )) | |
| printf "%s%${colWidth}s" "Every ${sleepTime}s: $*" "${dateNow}" | |
| tput sgr0 | |
| printf '%s\n' "" "" | |
| fi | |
| eval "$*" | |
| sleep "${sleepTime}" | |
| done | |
| } | |
| fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment