Setting Up Your Test Environment

The first thing you’ll need is a working instance of Bash. This is the default shell in the Terminal in Linux, Unix, BSD, and macOS (unless you’re running zsh). You can check which shell you’re running by typing the following command into your terminal: It should print out the shell that you’re using. My output tells me I’m using /bin/bash, which is exactly what I’m looking for. You’ll also need a text editor – whichever editor you choose should be fine. I’m using Nano in the terminal, but you could just as easily use Vim or Emacs in the terminal or something like Gedit, Kate, or Sublime in the GUI. Create a script file in your text editor, either by using the touch command or just typing your text editor name and the name of the file you want to create. For me, I could just type nano for-loop-test.sh, and I’d be golden.

The Bash For Loop: The Basics

The For loop in Bash tells the shell to iterate over a specified range of objects and execute a specified command on those objects. What does that mean? I think it may be easier to show you. This is a very basic For loop. The first line, for i in 1 2 3 4 5 specifies a variable “i” and a range 1 through 5. This could just as easily be some other, more complex sequence of numbers, or it could be a list of files input there or a directory. The next bit is basic formatting, with the command to be executed in the tabbed portion. do and done is part of the For loop syntax and have to be there. If I were to run this script, I’d get an output like this: You can see how that variable comes in. It helps you identify each individual object in that input range. To specify slightly more complex number ranges, you can use curly braces to set those up. To specify that same range from earlier, you could change for $i in 1 2 3 4 5 to for $i in {1..5}. The output would be the same. You can also have it count by certain numbers. This is counting out all the numbers by 3 between 0 and 27. Something that’s more common in scripts is executing a particular command on a bunch of files. If I wanted to use cat on a bunch of files in a directory, I could do that by changing the script to the following. This would print the output of all the files in “test-directory” to the terminal. The output would look like the following in my case. You can start to get an idea for how powerful the For loop can be. This is only scratching the surface, and you can string multiple commands together between do and done, and you can also use conditional statements to make the commands more complex. Don’t forget to check out our other Bash articles, like Bash Tips and Tricks to Work Smarter in the Terminal and some of the Bash special characters you should know.