- Shell script «for» loop syntax
- 11 Answers 11
- Linux for shell loop
- For Loops
- While Loops
- How to Use Bash For Loop with Examples in Linux
- Bash For Loop Syntax
- Bash For Loop Example
- Bash For Loop with Ranges
- Bash For Loops with Arrays
- Bash C Style For Loop
- Bash C-styled For Loops With Conditional Statements
- Use the ‘Continue’ statement with Bash For Loop
- Use the ‘break’ statement with Bash For Loop
Shell script «for» loop syntax
How can I get the compiler to realize it should treat $max as the other end of the array, and not part of a string?
what system and shell are you using? What kind of goofy system has sh or bash, but doesn’t have seq, a coreutil?
Small style nit: I usually see the do and then keywords on the same line as for and if , respectively. E.g., for i in <2..10>; do2..10>
11 Answers 11
Brace expansion, is performed before other expansions, so you cannot use that for variable length sequences.
Instead, use the seq 2 $max method as user mob stated.
So, for your example it would be:
max=10 for i in `seq 2 $max` do echo "$i" done
There is no good reason to use an external command such as seq to count and increment numbers in the for loop, hence it is recommend that you avoid using seq . This command is left for compatibility with old bash. The built-in commands are fast enough. for (( EXP1; EXP2; EXP3 )) .
@miller the for (( . )) syntax isn’t POSIX and that means for example that it won’t work out of the box on things like Alpine Linux. seq does.
Try the arithmetic-expression version of for :
This is available in most versions of bash, and should be Bourne shell (sh) compatible also.
@Flow: Hm, I just tried it on a couple of systems (Linux and BSD based) with #!/bin/sh and it worked fine. Invoked under bash and specifically under /bin/sh, still worked. Maybe the version of sh matters? Are you on some old Unix?
Very few systems have a dedicated sh , instead making it a link to other another shell. Ideally, such a shell invoked as sh would only support those features in the POSIX standard, but by default let some of their extra features through. The C-style for-loop is not a POSIX feature, but may be in sh mode by the actual shell.
Linux for shell loop
Most languages have the concept of loops: If we want to repeat a task twenty times, we don’t want to have to type in the code twenty times, with maybe a slight change each time.
As a result, we have for and while loops in the Bourne shell. This is somewhat fewer features than other languages, but nobody claimed that shell programming has the power of C.
For Loops
for loops iterate through a set of values until the list is exhausted: for.sh
#!/bin/sh for i in 1 2 3 4 5 do echo "Looping . number $i" done
Try this code and see what it does. Note that the values can be anything at all:
#!/bin/sh for i in hello 1 * 2 goodbye do echo "Looping . i is set to $i" done
This is well worth trying. Make sure that you understand what is happening here. Try it without the * and grasp the idea, then re-read the Wildcards section and try it again with the * in place. Try it also in different directories, and with the * surrounded by double quotes, and try it preceded by a backslash ( \* )
In case you don’t have access to a shell at the moment (it is very useful to have a shell to hand whilst reading this tutorial), the results of the above two scripts are:
Looping . number 1 Looping . number 2 Looping . number 3 Looping . number 4 Looping . number 5
and, for the second example:
Looping . i is set to hello Looping . i is set to 1 Looping . i is set to (name of first file in current directory) . etc . Looping . i is set to (name of last file in current directory) Looping . i is set to 2 Looping . i is set to goodbye
So, as you can see, for simply loops through whatever input it is given, until it runs out of input.
While Loops
while loops can be much more fun! (depending on your idea of fun, and how often you get out of the house. ) while.sh
#!/bin/sh INPUT_STRING=hello while [ "$INPUT_STRING" != "bye" ] do echo "Please type something in (bye to quit)" read INPUT_STRING echo "You typed: $INPUT_STRING" done
What happens here, is that the echo and read statements will run indefinitely until you type «bye» when prompted.
Review Variables — Part I to see why we set INPUT_STRING=hello before testing it. This makes it a repeat loop, not a traditional while loop.
The colon ( : ) always evaluates to true; whilst using this can be necessary sometimes, it is often preferable to use a real exit condition. Compare quitting the above loop with the one below; see which is the more elegant. Also think of some situations in which each one would be more useful than the other: while2.sh
#!/bin/sh while : do echo "Please type something in (^C to quit)" read INPUT_STRING echo "You typed: $INPUT_STRING" done
Another useful trick is the while read loop. This example uses the case statement, which we’ll cover later. It reads from the file myfile.txt , and for each line, tells you what language it thinks is being used.
(note: Each line must end with a LF (newline) — if cat myfile.txt doesn’t end with a blank line, that final line will not be processed.)
This reads the file » myfile.txt «, one line at a time, into the variable » $input_text «. The case statement then checks the value of $input_text . If the word that was read from myfile.txt was «hello» then it echo es the word «English». If it was «gday» then it will echo Australian . If the word (or words) read from a line of myfile.txt don’t match any of the provided patterns, then the catch-all «*» default will display the message «Unknown Language: $input_text» — where of course «$input_text» is the value of the line that it read in from myfile.txt . while3.sh
#!/bin/sh while read input_text do case $input_text in hello) echo English ;; howdy) echo American ;; gday) echo Australian ;; bonjour) echo French ;; "guten tag") echo German ;; *) echo Unknown Language: $input_text ;; esac done < myfile.txt
Let's say our myfile.txt file contains the following five lines:
this file is called myfile.txt and we are using it as an example input. hello gday bonjour hola
A sample run of this script would go like this:
$ ./while3.sh Unknown Language: this file is called myfile.txt and we are using it as an example input. English Australian French Unknown Language: hola
A handy Bash (but not Bourne Shell) tip I learned recently from the Linux From Scratch project is:
instead of the more cumbersome:
for runlevel in 0 1 2 3 4 5 6 S do mkdir rc$.d done
And this can be done recursively, too:
$ cd / $ ls -ld / drwxr-xr-x 2 root root 4096 Oct 26 01:00 /bin drwxr-xr-x 6 root root 4096 Jan 16 17:09 /lib drwxr-xr-x 2 root root 4096 Oct 27 00:02 /sbin drwxr-xr-x 2 root root 40960 Jan 16 19:35 usr/bin drwxr-xr-x 83 root root 49152 Jan 16 17:23 usr/lib drwxr-xr-x 2 root root 4096 Jan 16 22:22 usr/local/bin drwxr-xr-x 3 root root 4096 Jan 16 19:17 usr/local/lib drwxr-xr-x 2 root root 4096 Dec 28 00:44 usr/local/sbin drwxr-xr-x 2 root root 8192 Dec 27 02:10 usr/sbin
We will use while loops further in the Test and Case sections.
How to Use Bash For Loop with Examples in Linux
In programming languages, Loops are essential components and are used when you want to repeat code over and over again until a specified condition is met.
In Bash scripting, loops play much the same role and are used to automate repetitive tasks just like in programming languages.
In Bash scripting, there are 3 types of loops: for loop, while loop, and until loop. The three are used to iterate over a list of values and perform a given set of commands.
In this guide, we will focus on the Bash For Loop in Linux.
Bash For Loop Syntax
As mentioned earlier, the for loop iterates over a range of values and executes a set of Linux commands.
For loop takes the following syntax:
for variable_name in value1 value2 value3 .. n do command1 command2 commandn done
Let us now check a few example usages of the bash for loop.
Bash For Loop Example
In its simplest form, the for loop takes the following basic format. In this example, the variable n iterates over a group of numerical values enclosed in curly braces and prints out their values to stdout.
Bash For Loop with Ranges
In the previous examples, we explicitly listed the values to be iterated by the for loop, which works just fine. However, you can only imagine how cumbersome and time-consuming a task it would be if you were to iterate over, for example, a hundred values. This would compel you to type all the values from 1 to 100.
To address this issue, specify a range. To do so, specify the number to start and stop separated by two periods.
In this example, 1 is the first value whilst 7 is the last value in the range.
#!/bin/bash for n in ; do echo $n done
Once the shell script is executed, all the values in the range are listed, similar to what we had in simple loops.
Additionally, we can include a value at the end of the range that is going to cause the for loop to iterate through the values in incremental steps.
The following bash script prints the values between 1 and 7 with 2 incremental steps between the values starting from the first value.
#!/bin/bash for n in ; do echo $n done
From the above example, you can see that the loop incremented the values inside the curly braces by 2 values.
Bash For Loops with Arrays
You can also easily iterate through values defined in an array using a for Loop. In the following example, the for loop iterates through all the values inside the fruits array and prints them to stdout.
#!/bin/bash fruits=("blueberry" "peach" "mango" "pineapple" "papaya") for n in $; do echo $n done
The @ operator accesses or targets all the elements. This makes it possible to iterate over all the elements one by one.
In addition, you can access a single element by specifying its position within the array.
For example to access the “mango” element, replace the @ operator with the position of the element in the array (the first element starts at 0, so in this case, “mango” will be denoted by 2).
This is what the for loop looks like.
#!/bin/bash fruits=("blueberry" "peach" "mango" "pineapple" "papaya") for n in $; do echo $n done
Bash C Style For Loop
You can use variables inside loops to iterate over a range of elements. This is where C-styled for loops come in. The following example illustrates a C-style for loop that prints out a list of numerical values from 1 to 7.
Bash C-styled For Loops With Conditional Statements
You can include conditional statements inside C-styled for loops. In the following example, we have included an if-else statement that checks and prints out even and odd numbers between 1 and 7.
Use the ‘Continue’ statement with Bash For Loop
The ‘continue‘ statement is a built-in command that controls how a script runs. Apart from bash scripting, it is also used in programming languages such as Python and Java.
The continue statement halts the current iteration inside a loop when a specific condition is met, and then resumes the iteration.
Consider the for loop shown below.
#!/bin/bash for n in do if [[ $n -eq '6' ]] then echo "Target $n has been reached" continue fi echo $n done
This is what the code does:
- Line 2: Marks the beginning of the for loop and iterate the variable n from 1 to 10.
- Line 4: Checks the value of n and if the variable is equal to 6, the script echoes a message to stdout and restarts the loop at the next iteration in line 2.
- Line 9: Prints the values to the screen only if the condition in line 4 is false.
The following is the expected output after running the script.
Use the ‘break’ statement with Bash For Loop
The ‘break’ statement, as the name suggests, halts or ends the iteration when a condition is met.
Consider the For loop below.
#!/bin/bash for n in do if [[ $n -eq '6' ]] then echo "Target $n has been reached" break fi echo $n done echo "All done"
This is what the code does:
- Line 2: Marks the beginning of the for loop and iterate the variable n from 1 to 10.
- Line 4: Checks the value of n and if the variable is equal to 6, the script echoes a message to stdout and halts the iteration.
- Line 9: Prints the numbers to the screen only if the condition in line 4 is false.
From the output, you can see that the loop stops once the variable meets the condition of the loop.
Conclusion
That was a tutorial about Bash For loops. We hope you found this insightful. Feel free to weigh in with your feedback.