Nested for loops in Bash
In this article, we will discuss nested for loops in bash. First, we will quickly discuss the different for loop formulas available in bash. Next, we will discuss nested for loops with examples.
Bash for loop variants
First, let's look at the syntax of the for loop in bash:
for var in something
do
command
done
In this syntax, the variable name is the user's choice. There are multiple choices for something, which we will discuss later.
We can write any number of commands in the for body. There are several for loop variations in bash; we will see some of them shortly below.
for in the Range of Numbers
We can use a for loop to specify a list of numbers and iterate over those numbers one by one as shown in the following example:
for i in 1 3 8
do
echo $i
done
The loop will iterate over the given list of values (i.e. 1 3 8). In this particular example, the output will be:
1
3
8
for iterates over a list of values
We can define a list of values and iterate over that list as follows:
x=(1 3 8)
for i in ${x[@]}
do
echo $i
done
The result of this code will be the same as the output of the previous example. In the for loop statement, {x[@]}
it means: for each element of the list x`.
for range of sequence
We can give a range of values with a starting number followed by a double dot ..
and then an ending number. Similarly, we can put another pair of dots after a step.
For example, let's look at these two sample loop formulas:
for i in {1..3}
do
echo $i
done
echo "----------------------"
for i in {1..3..2}
do
echo $i
done
The output of this code will be:
1
2
3
----------------------
1
3
for words in string
We can define a list of words in a string separated by spaces and iterate over the words in the string like this:
names="Asim Babar Munir Ali"
for name in $names
do
echo $name
done
The output of this code will give the names in separate lines as shown below.
Asim
Babar
Munir
Ali
C-Style for Expression
We can for
give an expression in the loop similar to the for expression in C language. See the example:
for ((i=1;i<=5;i++))
do
echo $i
done
It will produce the following output:
1
2
3
4
5
Use of continue statement in for loop
We can put some conditions in the body of a for loop, followed by a continue
statement to skip the next body of the loop. See the example:
for ((i=1;i<=5;i++))
do
if [ $i == 3 ]
then
continue
fi
echo $i
done
Because of the if condition, the loop will skip the echo command for the value 3; therefore, the output will be: 1 2 4 5.
Looping through command line arguments
We can provide command line arguments to our bash script and run a for loop on the arguments separated by spaces. See the example:
for i in $@
do
echo "Script arg is $i"
done
In the first line, $@
the symbols represent a list of arguments separated by spaces. See the output of this example:
bash myscript.sh 13 28
Script arg is 13
Script arg is 28
Loop command output
We can run a for loop on the output of some command. See the example:
for f in $(ls)
do
echo "**** $f *****"
done
This script takes the output of the ls command and iterates over the values. See the example output:
**** first.c *****
**** second.c *****
**** third.c *****
Loop variable sequence
We can also run some inputs at runtime based on some variables. To do this, we can use seq 1 1 $n, where n can be a variable. See the example:
n=4
for i in $(seq 1 1 $n)
do
echo -n $i
echo " "
done
Here, I have assigned the value 4 to a variable, but it could be some count like word count etc. See the sample output:
1
2
3
4
Nested for loops in Bash
We have various nested for loops in bash. As per our requirement, we can create multiple variations of nested for loops i.e. by combining the available for loop formulas.
Here we will see multiple examples with output:
-
Print the first ten multiples of the first five positive integers.
The output of this code is:for number in {1..5} do for n in {1..10} do echo -n $((number*$n)) echo -n " " done echo "" done
1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50
-
Print the first 10 multiples of a list of integers.
The output of this code is:for number in 2 5 9 do for n in {1..10} do echo -n $((number*$n)) echo -n " " done echo "" done
2 4 6 8 10 12 14 16 18 20 5 10 15 20 25 30 35 40 45 50 9 18 27 36 45 54 63 72 81 90
-
Prints numbers in a triangular pattern.
The output of this code is:for number in {1..5} do for n in $(seq 1 1 $number) do echo -n $n done echo "" done
We may get several lines from command line arguments to print variable size patterns. See code:1 12 123 1234 12345
The output of the commandfor number in $(seq 1 1 $@) do for n in $(seq 1 1 $number) do echo -n $n done echo "" done
bash pattern2.sh 6
is:
where patter2.sh is the name of the script and 6 are the command line arguments.1 12 123 1234 12345 123456
-
Prints a triangle pattern with an asterisk (
*
) or any other character.
The output of the code with parameter 4 is:for number in $(seq 1 1 $@) do for n in $(seq 1 1 $number) do echo -n "*" done echo "" done
* ** *** ****
-
Print a message multiple times (for snippet).
The output is:messages="Sea_is_rough Don't_go_too_far_in_the_sea Remain_in_the_group Don't_take_kids_inside" for i in 1 2 3 4 5 do for message in $messages do echo $message done echo "----------------------------------" done
Sea_is_rough Don't_go_too_far_in_the_sea Remain_in_the_group Don't_take_kids_inside ---------------------------------- Sea_is_rough Don't_go_too_far_in_the_sea Remain_in_the_group Don't_take_kids_inside ---------------------------------- Sea_is_rough Don't_go_too_far_in_the_sea Remain_in_the_group Don't_take_kids_inside ---------------------------------- Sea_is_rough Don't_go_too_far_in_the_sea Remain_in_the_group Don't_take_kids_inside ---------------------------------- Sea_is_rough Don't_go_too_far_in_the_sea Remain_in_the_group Don't_take_kids_inside ----------------------------------
-
Printing on a line starts with a count of 1. You must print the count up to the command line argument list.
Bash counting.sh 4 5 8 The output of this code is:for number in $@ do for i in $(seq 1 1 $number) do echo -n "$i " done echo "" done
1 2 3 4 1 2 3 4 5 1 2 3 4 5 6 7 8
-
Print multiples of 10 through 20, but do not print multiples of the prime numbers in the sequence.
The output of this code is:for number in $(seq 10 1 20) do if [[ $number == 11 || $number == 13 || $number == 17 || $number == 19 ]] then continue fi for n in {1..10} do echo -n $((number*$n)) echo -n " " done echo "" done
Finally, we have multiple nested for loops in bash. So, we can combine the available for loop variants as needed to accomplish our task.10 20 30 40 50 60 70 80 90 100 12 24 36 48 60 72 84 96 108 120 14 28 42 56 70 84 98 112 126 140 15 30 45 60 75 90 105 120 135 150 16 32 48 64 80 96 112 128 144 160 18 36 54 72 90 108 126 144 162 180 20 40 60 80 100 120 140 160 180 200
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
How to decompress x.tar.xz format files under Linux
Publish Date:2025/04/08 Views:186 Category:OPERATING SYSTEM
-
A lot of software found today is in the tar.xz format, which is a lossless data compression file format that uses the LZMA compression algorithm. Like gzip and bzip2, it supports multiple file compression, but the convention is not to compr
Summary of vim common commands
Publish Date:2025/04/08 Views:115 Category:OPERATING SYSTEM
-
In Linux, the best editor should be vim. However, the complex commands behind vim's powerful functions also make us daunted. Of course, these commands do not need to be memorized by rote. As long as you practice using vim more, you can reme
Detailed explanation of command return value $? in Linux
Publish Date:2025/04/08 Views:58 Category:OPERATING SYSTEM
-
? is a special variable. This variable represents the return value of the previous command. That is to say, when we run certain commands, these commands will return a code after running. Generally, if the command is successfully run, the re
Common judgment formulas for Linux script shell
Publish Date:2025/04/08 Views:159 Category:OPERATING SYSTEM
-
In shell script programming, predicates are often used. There are two ways to use predicates, one is to use test, and the other is to use []. Let's take a look at how to use these two methods through two simple examples. Example 1 # test –
Shell script programming practice - specify a directory to delete files
Publish Date:2025/04/08 Views:98 Category:OPERATING SYSTEM
-
Usually, in Linux system we need to frequently delete some temporary files or junk files. If we delete them one by one manually, it will be quite troublesome. I have also been learning shell script programming recently, so I tried to write
Use of Linux command at - set time to execute command only once
Publish Date:2025/04/08 Views:158 Category:OPERATING SYSTEM
-
This article mainly involves a knowledge point, which is the atd service. Similar to this service is the crond service. The functions of these two services can be similar to the two functional functions of javascript. Those who have learned
Use of Linux command crontab - loop execution of set commands
Publish Date:2025/04/08 Views:170 Category:OPERATING SYSTEM
-
Compared with at , which executes a command only once, crontab, which we are going to talk about in this article, executes the set commands in a loop. Similarly, the use of crontab requires the support of the crond service. The service is s
Linux practice - regularly delete files under the directory
Publish Date:2025/04/08 Views:198 Category:OPERATING SYSTEM
-
Since we want to delete the files under the directory regularly, we need to use the Linux crontab command. And the content format of each work routine is also introduced in the format of each crontab work. Similarly, we need to use shell sc
How to use the Linux file remote copy command scp
Publish Date:2025/04/08 Views:151 Category:OPERATING SYSTEM
-
Scp copies files between two hosts over the network, and the data is encrypted during transmission. Its underlying layer uses ssh for data transmission. And it has the same authentication mechanism and the same security level as ssh. When u