for Loops
for loops are very practical, and work very well in Bash "one-liners"; mini scripts that are really just long commands designed to be executed directly at the terminal. This type of loop is used to perform a given set of commands for each item defined in a list.
From a high-level, this is what we're looking at:
for variable-name in <list>
do
<action to perform>
done
So, we will define a variable name, and that variable name will be used to represent each item in a defined list. The action we define will iterate over the list, replacing the placeholder we put in with the variable contents. With each pass, the variable content will be changed to the next item in the list, and this loop will continue until all items in the list have been run - or to put it another way, the loop will run FOR each item in the list.
Confused? Don't be, its a lot easier than it sounds. Take a look at the following example, which will be written as a "one-liner":
for ip in $(seq 1 10); do echo 192.168.1.$ip; done
So, let's quickly break this down:
We have defined a variable called
ip
, and we have also used theseq
command with command substitution. Allseq
does in this case is count upwards from the first number to the last, so the loop will start withip
holding the value of1
, then2
, and so on all the way up to10
. Simply put,seq
creates our list of values, which will like this: 1 2 3 4 5 6 7 8 9 10The command is split then by a
;
, which is a special character in Bash - it means "first complete the command to the left, THEN move on to the next bit". In this case, Bash willecho
the IP address192.168.1.$ip
, where$ip
contains the value of ourip
variable for this run of the loop. So on the first run, echo will print192.168.1.1
, then192.168.1.2
, and so on...The end of the "one-liner" contains another
;
, after which we seedone
. This signifies the end of the loop. So, the process will double back to the start, and continue to do so, until the final IP address with a value of .10, as per theseq
value at the start of the command
So, when we run this for loop "one-liner", we get the following outcome:

Last updated
Was this helpful?