Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Any examples for "loop" in bash?

for i in {1..5}; do echo $i; done
1
2
3
4
5

AND

for i in 1 2 3 4 5; do echo "Welcome $i times"; done
Welcome 1 times
Welcome 2 times
Welcome 3 times
Welcome 4 times
Welcome 5 times

AND

# {START..END..INCREMENT}
for i in {0..10..2}; do echo "Welcome $i times"; done
Welcome 0 times
Welcome 2 times
Welcome 4 times
Welcome 6 times
Welcome 8 times
Welcome 10 times

AND

for i in $(seq 1 3 20); do echo "Welcome $i times"; done
Welcome 1 times
Welcome 4 times
Welcome 7 times
Welcome 10 times
Welcome 13 times
Welcome 16 times
Welcome 19 times

AND

for (( c=1; c<=5; c++ )); do echo "Welcome $c times..."; done
Welcome 1 times...
Welcome 2 times...
Welcome 3 times...
Welcome 4 times...
Welcome 5 times...
share|improve this question

closed as not a real question by Michael Mrozek Aug 30 '11 at 14:26

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.If this question can be reworded to fit the rules in the help center, please edit the question.

5  
what's the question? –  enzotib Aug 30 '11 at 14:10
1  
"How do I use a for loop to do X" is a question; "Examples of loops" isn't, you can just search for a tutorial –  Michael Mrozek Aug 30 '11 at 14:26
    
I want to collect examples for "bash loop" - it could be very usefull! –  LanceBaynes Aug 30 '11 at 14:26

1 Answer 1

The for is superflous:

echo -e "\n"{1..5}

1 
2 
3 
4 
5

echo -e "\nWelcome "{1..5}" times"

Welcome 1 times 
Welcome 2 times 
Welcome 3 times 
Welcome 4 times 
Welcome 5 times

a recursive function:

toN () { max=$2 ; cur=$1; echo $cur; if (( cur < max )); then toN $((cur+1)) $max ; fi }
toN 0 5
0
1
2
3
4
5

a while-loop would be a bit boring, wouldn't it?

i=0; while ((i < 4)); do echo $((++i)); done ;

An not so very well known interactive loop in bash can be build with select:

select x in cat lolcat foo bar quit
do
  echo $x
  if [[ "$x" == "quit" ]]
  then
    break
  fi
done 

1) cat
2) lolcat
3) foo
4) bar
5) quit
#? 1
cat
#? 2
lolcat
#? 2
lolcat
#? 1
cat
#? 5
quit
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.