How to run a command multiple times, using bash shell?

Solution 1:

I don't think a command or shell builtin for this exists, as it's a trivial subset of what the Bourne shell for loop is designed for and implementing a command like this yourself is therefore quite simple.

Per JimB's suggestion, use the Bash builtin for generating sequences:

for i in {1..10}; do command; done

For very old versions of bash, you can use the seq command:

for i in `seq 10`; do command; done

This iterates ten times executing command each time - it can be a pipe or a series of commands separated by ; or &&. You can use the $i variable to know which iteration you're in.

If you consider this one-liner a script and so for some unspecified (but perhaps valid) reason undesireable you can implement it as a command, perhaps something like this on your .bashrc (untested):

#function run
run() {
    number=$1
    shift
    for i in `seq $number`; do
      $@
    done
}

Usage:

run 10 command

Example:

run 5 echo 'Hello World!'

Solution 2:

ps aux | grep someprocess looks like you want to watch changes of a program for a fixed time. Eduardo gave an answer that answer your question exactly but there is an alternative: watch:

watch 'ps aux | grep someprocess'

Note that I've put the command in single quotes to avoid the shell from interpreting the command as "run watch ps aux" and pipe the result through grep someprocess. Another way to do the previous command would be:

watch ps aux \| grep someprocess

By default, watch refreshes every two seconds, that can be changed using the -n option. For instance, if want to have an interval of 1 second:

watch -n 1 'ps aux | grep someprocess'

Solution 3:

Just for fun

pgrep ssh ;!!;!!;!!;!!;!!;!!

Solution 4:

Try this:

yes ls | head -n5 | bash

This requires the command to be executed in a sub-shell, a slight performance penalty. YMMV. Basically, you get the "yes" command to repeat the string "ls" N times; while "head -n5" terminated the loop at 5 repeats. The final pipe sends the command to the shell of your choice.

Incidentally csh-like shells have a built-in repeat command. You could use that to execute your command in a bash sub-shell!


Solution 5:

similar to previous replies, but does not require the for loop:

seq 10 | xargs -I -- echo "hello"

pipe output of seq to xargs with no arguments or options

Tags:

Linux

Bash