Table of Contents
Using for
Loop with seq
Command
To loop from 1
to 10
in the Bash shell:
- Use the
for
keyword to start thefor
loop. - Use
i
as a loop variable, which is accountable for taking values from1
to10
. - Use the
$(seq 1 10)
expression, which is a command substitution executing theseq
command to produce a sequence of numbers from1
to10
. - Use the
do
keyword to mark the starting of thefor
loop’s body. - Use the
echo
command to print the value of thei
variable on the bash console that we created in step-2. - Use the
done
keyword to mark thefor
loop’s end.
1 2 3 4 5 |
for i in $(seq 1 10); do echo $i; done |
1 2 3 4 5 6 7 8 9 10 11 12 |
1 2 3 4 5 6 7 8 9 10 |
Here, we used the seq
command, which is used in Linux to generate a sequence of numbers from the specified FIRST
to the specified LAST
in steps of INCREMENT
. This command is helpful for loops such as for
and while
, etc.
We can use the seq
command in the following three ways:
seq 10
– this command will generate numbers starting from1
to10
by increment1
.seq 2 10
– this command will generate numbers starting from2
to10
by incrementing1
.seq 2 2 10
– this command will generate numbers beginning from2
to10
by incrementing2
.
In the
seq
command, the first value is the starting number, the last value is the ending number, and the middle value represents the increment.
Using for
Loop with C-sytle
Syntax
To loop from 1
to 10
in the Bash shell:
- Use the
for
keyword to start thefor
loop. - Use
j
to hold the value from1
to10
incremented by1
(one value in each iteration). - Use the
do
keyword to mark the starting of thefor
loop’s body. - Use the
echo
command to print the value of thei
variable on the bash console we created in step-2. - Use the
done
keyword to mark thefor
loop’s end.
1 2 3 4 5 |
for ((j=1;j<=10;j++)); do echo $j; done |
1 2 3 4 5 6 7 8 9 10 11 12 |
1 2 3 4 5 6 7 8 9 10 |
Using for
Loop with Curly Braces
To loop from 1
to 10
in the Bash shell:
- Use the
for
keyword to start thefor
loop. - Use
i
to hold the value from1
to10
incremented by1
(one value in each iteration). - Use curly braces with the
..
operator as{1..10}
to specify the range; here, it is1
to10
. - Use the
do
keyword to mark the starting of thefor
loop’s body. - Use the
echo
command to print the value of thei
variable on the bash console we created in step-2. - Use the
done
keyword to mark thefor
loop’s end.
1 2 3 4 5 |
for i in {1..10}; do echo $i; done |
1 2 3 4 5 6 7 8 9 10 11 12 |
1 2 3 4 5 6 7 8 9 10 |
That’s all about Bash for loop 1 to 10.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.