Created
September 2, 2012 16:04
-
-
Save rmascarenhas/3600932 to your computer and use it in GitHub Desktop.
repeat a command in bash
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
#!/usr/bin/env bash | |
# repeat.sh | |
# | |
# Usage: | |
# repeat <command> | |
# will repeat <command> forever. | |
# | |
# repeat -nN <command> | |
# will repeat <command> N times. | |
# | |
# repeat -iT <command> | |
# will repeat <command> every T seconds. | |
fail() { | |
echo "$1" >&2 | |
exit 1 | |
} | |
declare -i times interval | |
times=-1 | |
interval=0 | |
while getopts 'n:i:' option; do | |
case $option in | |
n) | |
let "times = $OPTARG" | |
;; | |
i) | |
let "interval = $OPTARG" | |
;; | |
esac | |
done | |
shift $((OPTIND - 1)) | |
if [[ $# == 0 ]]; then | |
fail "Usage: $0 [-n-i] COMMAND" | |
fi | |
test $times -gt 0 | |
infinite_loop=$? | |
command=$* | |
while (( $times > 0 || $infinite_loop )); do | |
eval "$command" & | |
((times--)) | |
if (( $times > 0 || $infinite_loop )); then | |
sleep $interval | |
fi | |
done | |
wait |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment