Creating Bash Loops With Examples

In this post I will be showing you how to use a variety of bash loops to make your life easier. I will try to explain how they work as basic as I can, if you need help feel free to comment below and I will try to help you out. One of the great things about loops is that you can use them directly from the shell prompt, you do not need to create a file/script for these.

Bash For Loops

Lets start this post by looking at for loops, basically scripts that will cycle through and run your commands on whatever info is provided.

In the above example, we are basically telling the script to set each drive/file system to a temporary variable named a which we can call with $a. You can change the variable name to anything you like but for this example we will just use “a”. Next we have to add “;do” which will make our loop run the actual commands we want. Above I set it up so that it would return any drives or file systems. You can see an example output below:

Bash For Loop Screenshot

Another way you can use for loops is by defining exactly what you want the script to loop through, for example if we wanted to ping 2 hosts to see that they are up. In the example below we will specifically tell the loop to run a ping check on google.com and bing.com:

The result will be something like this:

For Loop Ping Hosts

If you wanted to make a loop that counts, you can easily do so by tweaking the first line. The example below will show you how to make a simple bash counting for loop.

Bash Counting For Loop

Bash While Loops

While loops are great for things such as infinite loops or re-running commands until they succeed, as-well as some other purposes. I will start this off with an infinite loop. To escape an infinite loop you can do one of two things: you can press ctrl+c or you can add a ‘break’. I will show you how to use breaks in the next example.

Bash Infinite Loop

Next up is how to use breaks to escape from infinite loops, this is very useful if you want to keep retrying a command and exit the loop once it finishes successfully. The way we will accomplish this is by adding “&& break” to the end of whatever command is being run. The && means that if this command executes successfully then run this command, if not then don’t run it.

For this example to work we will use another terminal and create the file while this loop is running using “echo error > /tmp/fakelog”. You may need to use sudo/root to create this tmp file.

Using Breaks In Bash Loops

There are more loops for example the until loop, I will write about them in the future.

I hope you enjoyed this post, please don’t forget to like/share/comment! 🙂

Comments (1)

Leave a Reply

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