When working with batch processing tasks—such as encoding video files, image processing, or running a series of API calls—you often need to execute the same script multiple times, sometimes with a short delay between runs. Instead of manually running the script or writing a separate looping script each time, you can streamline the process by adding a simple function to your shell configuration.
The loop
Function
This handy loop
function allows you to repeatedly execute a command a specified number of times, optionally adding a delay between executions:
loop() {
if [ "$#" -lt 2 ]; then
echo "Usage: loop <number_of_times> [sleep_duration] <command> [args...]"
return 1
fi
local count=$1
shift
local sleep_duration=0
if [[ "$1" =~ ^[0-9]+([.][0-9]+)?$ ]]; then
sleep_duration=$1
shift
fi
for ((i = 1; i <= count; i++)); do
"$@"
if [ "$i" -lt "$count" ]; then
sleep "$sleep_duration"
fi
done
}
How It Works
- Argument Parsing:
- The function expects at least two arguments: the number of times to repeat the command and the command itself.
- If the second argument is a valid number, it’s treated as the sleep duration before each iteration.
- Loop Execution:
- The command runs the specified number of times.
- If a sleep duration is provided, it waits between executions.
Example Use Cases
Running a Python Script on Multiple Video Files
Imagine you have a Python script that processes video files and moves on to the next one when it finishes. You can run it multiple times with a short pause between executions:
loop 5 2 python process_video.py
This will:
- Run
python process_video.py
5 times. - Pause for 2 seconds between each run.
Testing an API Endpoint
If you’re testing an API and want to make repeated requests with a delay, you can use:
loop 10 1 curl -X GET https://api.example.com/data
This sends 10 GET requests, with a 1-second pause between each.
Running Background Jobs
You can also use this function to restart a script multiple times in the background:
loop 3 5 ./restart_service.sh &
Why Use This Instead of a While Loop?
While you could write a while
loop in your terminal, this function:
- Saves typing by handling looping and delays for you.
- Prevents common mistakes like infinite loops.
- Can be easily reused across multiple tasks.
Final Thoughts
By adding this loop
function to your shell configuration, you create a versatile and reusable tool for automating repetitive tasks. Whether you’re processing files, making API calls, or running background jobs, this simple function can save you time and effort.
Give it a try and tweak it to fit your workflow!