bash 中有“循环”的例子吗?
for i in {1..5}; do echo $i; done
1
2
3
4
5
和
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
和
# {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
和
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
和
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...
答案1
for 是多余的:
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
递归函数:
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
while 循环会有点无聊,不是吗?
i=0; while ((i < 4)); do echo $((++i)); done ;
bash 中不太为人所知的交互式循环可以使用以下命令构建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