Skip to main content

Looping a Command in Linux

You can use a while loop to repeatedly execute a command in the Linux terminal. Here is a simple example that will loop the make test command indefinitely:

while true; do
make test
# If you want a pause between loops, use the sleep command
# sleep 1 # Pause for 1 second
done

You can save this script to a file, such as loop_make_test.sh, then give it execute permission and run it in the terminal:

chmod +x loop_make_test.sh
./loop_make_test.sh

Or you can enter the while loop command directly in the terminal.

If you want to stop the loop after a certain number of iterations, you can use a counter:

count=0
max_count=10 # Set the maximum number of loops

while [ $count -lt $max_count ]; do
make test
count=$((count+1)) # Increment the counter
# sleep 1 # Pause here if needed
done

If you need to stop the loop when make test fails, you can check the exit status of the make command:

while true; do
make test
if [ $? -ne 0 ]; then
echo "make test failed"
break
fi
# sleep 1 # Pause here if needed
done

In this script, $? represents the exit status of the previous command. If make test returns a non-zero status (which typically indicates an error), the loop will stop.