repeat-command
Linux Commands – Repeat a Command n Times
1. Introduction
In this quick tutorial, we’ll present how to perform an operation n times using different approaches.
2. Using a for Loop
Let’s start by defining a task that we’ll use throughout our examples. To make things simple, we’ll print the word “Command” out to the console five times. We’ll also include an iteration number wherever possible.
Let’s jump straight into it and start with the good old “for-loop”:
for i in {1..5}
do
echo "Command no. $i"
done
The above example results in the output:
Command no. 1
Command no. 2
Command no. 3
Command no. 4
Command no. 5
We can also condense those operations into a one-line solution:
for i in {1..5}; do echo "Command no. $i"; done
For the scenarios where we need the condition-based expressions, we can use a more programming-style approach as well:
for ((i=0;i<5;i++)); do echo "Command no. $i"; done
3. Using a while Loop
i=1
while [[i -le 5 ]]; do
echo "Command no. $i"
let ++i;
done
As in the previous example, we can implement this loop in just one line:
i=1; while [[i -le 5 ]]; do echo "Command no. $i"; let ++i; done
4. Using seq with xargs
According to Linux documentation, seq prints sequences of numbers and xargs constructs an argument list and executes the specified command on each argument.
With that in mind, we can pipe those two operations to create a repeatable command:
seq 5 | xargs -I{} echo "Command no. {}"
In the above example, we used the -I flag with placeholder string “\{}”. The placeholder in the defined command is then replaced with a sequenced number, resulting in the same output we saw above.
5. Bash Functions
If we want to use repeatable commands often, we can rewrite one of our examples into a bash function:
function repeat(){
for ((i=0;i<$1;i++)); do
eval ${*:2}
done
}
We can now use our function in the shell:
repeat 5 echo "Command"
In the above example, we used eval to be able to use commands that are not executables, like variable assignments.
We also introduced $\{*:2} which evaluates to an array of all the command input variables, starting from the index 2.
As our implementation accepts multiple arguments, we can also pass multiple commands to our repeat function:
repeat 5 echo "Command" ";" echo "Another command"