Table of Contents
Using for Loop with seq Command
To loop from 1 to 10 in the Bash shell:
- Use the
forkeyword to start theforloop. - Use
ias a loop variable, which is accountable for taking values from1to10. - Use the
$(seq 1 10)expression, which is a command substitution executing theseqcommand to produce a sequence of numbers from1to10. - Use the
dokeyword to mark the starting of theforloop’s body. - Use the
echocommand to print the value of theivariable on the bash console that we created in step-2. - Use the
donekeyword to mark theforloop’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 from1to10by increment1.seq 2 10– this command will generate numbers starting from2to10by incrementing1.seq 2 2 10– this command will generate numbers beginning from2to10by incrementing2.
In the
seqcommand, 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
forkeyword to start theforloop. - Use
jto hold the value from1to10incremented by1(one value in each iteration). - Use the
dokeyword to mark the starting of theforloop’s body. - Use the
echocommand to print the value of theivariable on the bash console we created in step-2. - Use the
donekeyword to mark theforloop’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
forkeyword to start theforloop. - Use
ito hold the value from1to10incremented by1(one value in each iteration). - Use curly braces with the
..operator as{1..10}to specify the range; here, it is1to10. - Use the
dokeyword to mark the starting of theforloop’s body. - Use the
echocommand to print the value of theivariable on the bash console we created in step-2. - Use the
donekeyword to mark theforloop’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.