#!/bin/bashfor((i=0;i<10;i++))doecho"WELCOME TO BEIJING $i"done
运行结果:
WELCOME TO BEIJING 0
WELCOME TO BEIJING 1
WELCOME TO BEIJING 2
WELCOME TO BEIJING 3
WELCOME TO BEIJING 4
WELCOME TO BEIJING 5
WELCOME TO BEIJING 6
WELCOME TO BEIJING 7
WELCOME TO BEIJING 8
WELCOME TO BEIJING 9
Shell编程独有的for循环类型:
伪代码表示:
for 变量 in 单词列表
do循环体
done
单词列表的注意事项:
1.列表之间用空格分隔;
2.列表是连续的,可以使用以下格式:
{数字1..数字n}
也能用序列表示,例如,从1开始,到100结束:
`seq 1 100`
若有间隔,比如:从1开始,到100结束,每间隔5个值,取一个值,可以改写成:
`seq 1 5 100`
3.单词列表也可以是命令的结果,需要注意的是命令的结果要使用空格进行分隔;
4.省略语句in和单词列表的for循环,这时执行来自终端命令行的参数;
示例代码:
#!/bin/bashfor i in whoami lspwddo$i
done
echo"-------------------------------------"for i in `seq 0 10 100`
doecho"WELCOME TO BEIJING $i "done
echo"-------------------------------------"for i in {1..5}doecho"WELCOME TO BEIJING $i "
done
echo"-------------------------------------"for i in WELCOME TO BEIJING
doecho-n "$i "done
echo" "echo"-------------------------------------"for i
doecho"WELCOME TO BEIJING $i "
done
echo"-------------------------------------"for i in `ls*.c`
dochmod 777 $i
done
运行结果:
#bash xxx.sh i love you
linux
f1.c f2.c f3.c g1.sh g2.sh g3.sh
/home/linux/xxxx
-------------------------------------
WELCOME TO BEIJING 0
WELCOME TO BEIJING 10
WELCOME TO BEIJING 20
WELCOME TO BEIJING 30
WELCOME TO BEIJING 40
WELCOME TO BEIJING 50
WELCOME TO BEIJING 60
WELCOME TO BEIJING 70
WELCOME TO BEIJING 80
WELCOME TO BEIJING 90
WELCOME TO BEIJING 100
-------------------------------------
WELCOME TO BEIJING 1
WELCOME TO BEIJING 2
WELCOME TO BEIJING 3
WELCOME TO BEIJING 4
WELCOME TO BEIJING 5
-------------------------------------
WELCOME TO BEIJING
-------------------------------------
WELCOME TO BEIJING i
WELCOME TO BEIJING love
WELCOME TO BEIJING you
-------------------------------------