Created
March 31, 2011 22:13
-
-
Save saimonmoore/897373 to your computer and use it in GitHub Desktop.
A bash function that executes a command n (default 5) times
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
# Usage: | |
# $loopc echo 'hello world' | |
# hello world | |
# hello world | |
# hello world | |
# hello world | |
# hello world | |
# | |
#(i.e. defaults to 5 iterations) | |
# | |
# $loopc 3 echo 'hello world' | |
# hello world | |
# hello world | |
# hello world | |
# | |
function loopc { | |
args=("$@") | |
if [ $1 -ge 0 2>/dev/null ] | |
then | |
LIMIT=$1 | |
unset args[0] | |
else | |
LIMIT=5 | |
fi | |
for i in $(eval echo "{1..$LIMIT}"); do | |
$(eval echo "${args[@]}"); | |
done | |
} |
In particular if I want to quit midway, currently I need to quit (^c) for the n iterations that are left. (Not nice if you do loopc 50 bla). I guess rewriting this in ruby is an option for that case :)
Hi Saimon, do you mind if I barge in? Well, I'd say that it's not recommended to have optional positional arguments, you won't be able to tell a time from a command. So you either make it required (see my fork) or use getopt/getops. And no need to use evals, just execute "$@" after shifting the undesired arguments.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please try and improve this code and let me know.