Sometimes we want to repeat a command on Linux, and we can use the following BASH function to repeat a command for a number of times:
function repeat() {
COUNT=$2
if [[ -z "$COUNT" ]]; then
COUNT=100
fi
for i in $(seq 1 $COUNT); do
echo Counter=$i: CMD=$1
if ! $1; then
echo "Error! $i"
return 1
fi
done
return 0
}
TO use, this is an example:
$ repeat "echo hello!" 10
The second parameter specifies the number of times to run, and by default it is 100 times. We can use this command to repeat some tests, to find out if a test is flakey or not (stress testing). If at some point, the command/test failed, the loop will be terminated early.
Retry each command
We can also modify this function to let each run retry a few times, for example, the third parameter specifies the retry for each run, by default it is 2.
function repeat() {
CMD=$1
COUNT=$2
RETRY=$3
TOTAL=0
if [[ -z "$COUNT" ]]; then
COUNT=500
fi
if [[ -z "$RETRY" ]]; then
RETRY=2
fi
echo "Running Total $COUNT times."
for i in $(seq 1 $COUNT); do
SUCC=0
for j in $(seq 1 $RETRY); do
echo Counter=$i: CMD=$CMD, RETRY=$j
if ! $CMD; then
echo "Error! $CMD - RETRY=$j"
TOTAL=$((TOTAL+1))
sleep 3
else
SUCC=1
break
fi
done
if [[ "${SUCC}" == "0" ]]; then
echo "Failed at $COUNT runs, total retries = $TOTAL"
return 1
fi
done
echo "OK at $COUNT runs, total retries = $TOTAL"
return 0
}
TLDR; this post presents a simple BASH function which is useful to repeat some command a few times, and we can also specify the retry for each run. This command may be useful in stress testing.
BASH Programming/Shell
- Alarming on High Disk Usage using BASH, AWK, Crontab Job
- Compute GCD in Bash with Input Validation
- Why a Leading Space in Linux Shell Commands Can Matter?
- How to Get HTTP Response Code using cURL Command?
- Three Interesting/Fun BASH Commands
- One Interesting Linux Command (Steam Locomotive in BASH)
- Simple Bash Function to Repeat a Command N times with Retries
- How to Extract a Domain Name from a Full URL in BASH?
- BASH Function to Compute the Greatest Common Divisor and Least Common Multiples
- BASH Function to Get Memory Information via AWK
- BASH Function to Escape Parameters Argument
- BASH Function to Check if sudo Available
- Full Permutation Algorithm Implementation in BASH
- BASH Function to Install Docker
- A Simple BASH Function/Script to Run a Command in Background
- BASH Script to Compute the Average Ping to a Domain
- A Bash Process Controller to Start, Stop and Restart an Daemon Program
- Linux BASH shell - Echo This if you get angry
- Bash SHELL, Chess Board Printing
–EOF (The Ultimate Computing & Technology Blog) —
Last Post: Teaching Kids Programming - N-Repeated Element in Size 2N Array (Math)
Next Post: Teaching Kids Programming - N-Repeated Element in Size 2N Array (Random Algorithm)