Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save saimonmoore/897373 to your computer and use it in GitHub Desktop.
Save saimonmoore/897373 to your computer and use it in GitHub Desktop.
A bash function that executes a command n (default 5) times
# 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
}
@saimonmoore
Copy link
Author

Please try and improve this code and let me know.

@saimonmoore
Copy link
Author

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 :)

@tokland
Copy link

tokland commented Aug 22, 2011

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