How to Use BASH for Loop

One of the most basic tricks when authoring bash scripts involves making a loop so that you can have a certain task executed automatically several times over. Eventually, the loop will reach a predetermined test condition and suddenly cease to execute. Loops like these will work perfectly in bash on Linux and macOS as well as the bash shell inside Windows 10 and even the various shells in FreeBSD. Naturally, you can write whatever command you’d prefer in any loop and keep any process going any amount of time you’d like. While we’ll write some extremely simple loops, you can use these skills to author whatever kinds of scripts you’d like.

There are many ways to start writing a script, but for this discussion we’ll assume that you’ve opened a command prompt either by searching for terminal on the Dash, by clicking on it in the KDE, MATE, LX or Whisker menus or by holding down Ctrl, Alt and T at the same time. While we’ll discuss vi/vim and nano as editors, the issue of which editor to use is quite personal and you could work with whatever you feel comfortable with.

Method 1: The until Loop

Perhaps the most basic loop in bash is the until loop. It will keep executing commands until the test condition you set becomes true. We’ll assume you’ve used either nano or vi to open a non-existent file called until.sh and are ready to insert fresh text into it. We’ll just make something that counts to 20 in your terminal to keep this easy at first.

Start by typing in the following:

#!/bin/bash

n=0

until [ $n -gt 20 ]

do

echo $n

((n++))

done

If you’re using nano, then save it by holding down Ctrl and then pushing O and finally X to exit. Users of vi will want to push escape then type :wq to save and quit.

Next type chmod +x untilLoop at the prompt to make it executable and then type ./untilLoop to run it. Once it runs, the loop will keep printing new numbers out on your terminal until the n variable gets to 20.

By the way, the first line tells your environment which shell to load up when working with these scripts. Some programmers advise only ever using #!/bin/sh to ensure that your script adheres to certain POSIX standards, but these simple scripts shouldn’t have any problem running on the vast majority of modern systems.

Method 2: The for Loop

A for loop takes a look at every item in a given list and then performs a given set of commands on that list. We’ll make one that prints out some operating system names but keep in mind again that you could be doing anything with this if you’d like.

Type either nano forLoop or vi forLoop at the command prompt and start entering this following script. Users of vi will have to enter insert mode before they do so.

#!/bin/bash

unices=’GNU/Linux FreeBSD OpenBSD NetBSD Solaris OpenIndiana Darwin HP-UX Minix’

for unix in $unices

do

echo $unix

done

Save the file again using either the Ctrl+O and then Ctrl+X method in nano or the Esc then :wq method in vi before issuing the command chmod +x forLoop to make it executable. Once you have, run it by typing ./forLoop at the prompt. The for loop forces the echo command to work on each of the items in the unices variable in turn. You could, once more, replace that list with any argument and replace echo with any command to automate long processes.

Method 3: The while Loop

Start editing a third file called whileLoop using nano, vi or whichever other editors you’d like to use. If you’d prefer to use a graphical text editor, then you could actually do that as well with any of these projects as long as you make sure to put the file in the same directory that you’re working from inside of the command prompt.

Inside this file, you’ll want to add the lines:

#!/bin/bash

n=0

while [ $n -le 20 ]

do

echo $n

((n++))

done

Save the file the same way that you saved the others and then exit your text editor. Once you’ve exited, then issue the command chmod +x whileLoop to allow you to execute it and then run ./whileLoop to run it. You’ll see the same output that came out of the untilLoop script from the first method as it counts from 0 to 20 in more than likely a split second.

This is an excellent demonstration of the fact that there’s more than one way to do things whenever you’re working with loops in this fashion. While there’s technically no wrong way to do so, you’ll probably come across script authors who claim that you should write your scripts closer to the way the C programming language does things or alternatively, others might suggest that you shouldn’t do this. Honestly, there are probably many correct ways to solve a problem.

Feel free to delete your scripts once you’re done practicing with them.

Kevin Arrows
Kevin is a dynamic and self-motivated information technology professional, with a Thorough knowledge of all facets pertaining to network infrastructure design, implementation and administration. Superior record of delivering simultaneous large-scale mission critical projects on time and under budget.

Expert Tip

How to Use BASH for Loop

If the issue is with your Computer or a Laptop you should try using Restoro which can scan the repositories and replace corrupt and missing files. This works in most cases, where the issue is originated due to a system corruption. You can download Restoro by clicking the Download button below.

Download Now

I'm not interested