Skip to content

Instantly share code, notes, and snippets.

@rmascarenhas
Created September 2, 2012 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmascarenhas/3600932 to your computer and use it in GitHub Desktop.
Save rmascarenhas/3600932 to your computer and use it in GitHub Desktop.
repeat a command in bash
#!/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