Using Basic Loops In Bash Scripts

In this post I will be showing you how to use some of the basic loop functions available in bash scripting. These loops (especially a basic for loop) come in handy and are used pretty much daily for me. You can run these loops directly from the terminal, you do not need to actually save them as a script to execute them which makes them even more useful. I will get into using loops to iterate through arrays and other useful tricks on a later post so keep an eye out if you liked this one! =)

Basic For Loop

So lets get started with a basic bash for loop, this loop basically goes through each line or entry depending on how you run it. Then it will run whatever commands or functions you specify inside of the loop. You can change the for a variable to anything you like, however you will also need to change the for line to reflect it. Here are a few examples of some basic bash for loops.


for line in `cat listofwords.txt`; do # Start loop for each line in text file
# Do this command for each line in text file
echo "$line";
done; # Finish loop

for drive in /dev/sd[a-z]; do # Start loop for any drives found
# Do this command for each drive found
smartctl -HAi "$drive";
done; # Finish loop

for a in '/dev/sda' '/dev/sdb' '/dev/sdc'; do # Start loop for 3 specific values
# Do this command for specified drives
smartctl -HAi "$a";
done; # Finish loop

for a in {1..4}; do # Start loop and count through 1,2,3,4
# Do the command for each iteration
echo "$a";
done; # Finish loop

While Loop

While loops are very handy when you want something to continue looping until a condition is met OR is no longer met. For example we can use a while loop to ping a server that is booting and then notify us when its pingable. Here is an example of a while loop below, if you need a while loop that counts on a positive result instead of a negative like this example then simply remove the “!”.


while ! (ping -c 1; do # While this condition is not met
# Do this command
echo "Unable to ping it!";
done; # Finish loop

echo "Loop ended which means server is up!"

Infinite Loop

To create an infinite bash loop, you will use a while loop with the argument being simply “true”. Since true is always true, the loop never ends unless you kill it with ctrl+c. Please note that depending on what you are doing with the loop, you may need to add a sleep command otherwise it will be annoying/difficult to terminate. Here is an example of an infinite loop in bash.


while (true); do # Start infinite loop
# Do these commands while loop is active
  echo "Looping..."; 
  sleep 1; # Added for easier exiting of infinite loop
done; # Finish loop

Congratulations, you now know how to create basic loops in bash scripts. Please don’t forget to like/comment/share, thanks!

You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *