Sunday, August 12, 2007

Using the UNIX repeat Command

The other day I was thinking about all those sentences I had to write while in grade school (primary). It would have been great to know something about the repeat command. In all seriousness, you can use it as a separator (maybe script output). Here are some examples of its use.

# repeat 5 echo "*********"
*********
*********
*********
*********
*********
# repeat 5 echo "##########"
##########
##########
##########
##########
##########
# repeat 5 echo " "





# repeat 500 echo "I will not chew gum or backtalk."
I will not chew gum or backtalk.
I will not chew gum or backtalk.
I will not chew gum or backtalk.
I will not chew gum or backtalk.
I will not chew gum or backtalk.
...
You get the idea

3 comments:

Cian said...

Just to clarify, this is not a globally available command, it's a zsh, csh or tcsh builtin, but not available in sh or bash.

Mihai said...

here's your repeat command

#!/bin/sh

times=$1
command=$2
if [ "$times" = "" || "$command" = "" ] ; then
echo "Usage: $0 times command"
fi
$i=0;
while true ; do
`$command`
let i=$i+1
if [ $i -ge $times ] ; then
break ;
fi
done

Joe Clark said...

mihai's script doesn't work. Here's the closest thing to his original I could come up with:

#!/bin/sh

times=$1; shift
if [ "$times" = "" -o "$1" = "" ] ; then
echo "Usage: $0 times command [args ...]"
exit 1
fi
i=0
while true ; do
"$@"
let i=$i+1
if [ $i -ge $times ] ; then
break
fi
done