I want to write a nested for loop that has to work in the bash shell prompt. nested for loop in Single line command.
For example,
for i in a b; do echo $i; done a b In the above example, for loop is executed in a single line command right. Like this I have tried the nested for loop in the shell prompt. Its not working. How to do this. Please update me on this.
43 Answers
The question does not contain a nested loop, just a single loop. But THIS nested version works, too:
# for i in c d; do for j in a b; do echo $i $j; done; done c a c b d a d b 6On one line (semi-colons necessary):
for i in 0 1 2 3 4 5 6 7 8 9; do for j in 0 1 2 3 4 5 6 7 8 9; do echo "$i$j"; done; done Formatted for legibility (no semi-colons needed):
for i in 0 1 2 3 4 5 6 7 8 9 do for j in 0 1 2 3 4 5 6 7 8 9 do echo "$i$j" done done There are different views on how the shell code should be laid out over multiple lines; that's about what I normally use, unless I put the next operation on the same line as the do (saving two lines here).
#!/bin/bash # loop*figures.bash for i in 1 2 3 4 5 # First loop. do for j in $(seq 1 $i) do echo -n "*" done echo done echo # outputs # * # ** # *** # **** # ***** for i in 5 4 3 2 1 # First loop. do for j in $(seq -$i -1) do echo -n "*" done echo done # outputs # ***** # **** # *** # ** # * for i in 1 2 3 4 5 # First loop. do for k in $(seq -5 -$i) do echo -n ' ' done for j in $(seq 1 $i) do echo -n "* " done echo done echo # outputs # * # * * # * * * # * * * * # * * * * * for i in 1 2 3 4 5 # First loop. do for j in $(seq -5 -$i) do echo -n "* " done echo for k in $(seq 1 $i) do echo -n ' ' done done echo # outputs # * * * * * # * * * * # * * * # * * # * exit 0 2