1 for写法:
for 变量 in 列表; do
循环体
done
for中列表的出现形式有如下两种:
{1..100} 表示从1到100
`seq 1 2 10` 表示从1开始 间隔2个 到10为止
for 写法方式2:
for (( expr1 ; expr2 ; expr3 )); do
循环体
done
案例:
1 求1-100的总和 root@chinadaas109 zhoumingtest]# cat fortest.sh #!/bin/sh # declare -i sum=0 for i in {1..100}; do sum=$[$sum+$i] done echo "sum is: $sum" 2 依次向/etc/passwd中的每个用户问好 LINES=`wc -l /etc/passwd|cut -d' ' -f1` for I in `seq 1 $LINES`; do echo "Hello, `head -n $I /etc/passwd | tail -1 | cut -d: -f1`"; done
打印1到10之间的奇数 $ cat test.sh #!/bin/bash # for i in `seq 1 2 $1`; do echo $i done result: $ sh test.sh 10 1 3 5 7 9
将1-100的奇偶和打印出来:
[root@chinadaas109 zhoumingtest]# cat test.sh #!/bin/bash # declare -i evensum=0 declare -i oddsum=0 for i in {1..100}; do if [ $[$i%2] -eq 0 ]; then let evensum+=$i else let oddsum+=$i fi done echo "evensum is: $evensum" echo "oddsum is: $oddsum"
打印1-100的和:
#!/bin/bash # declare -i sum=0 for((i=1; i<=100; i++)); do let sum+=$i done echo $sum
2 case语句
语法:
case SWITCH in value1) statement ... ;; value2) statement ... ;; *) *表示其余情况下的意思 statement ... ;; esac 是 case反过来写
使用案例:
根据输入不同的字符 显示不同的结果 #!/bin/bash # case $1 in [0-9]) echo "a digit." ;; [a-z]) echo "Lower." ;; [A-Z]) echo "Upper." ;; *) echo "Special character." ;; esac只接受参数start,stop,restart,status其中之一:
只接受参数start,stop,restart,status其中之一 #!/bin/bash # case $1 in 'start') echo "start server ..." ;; 'stop') echo "stop server ..." ;; 'restart') echo "restart server ..." ;; 'status') echo "status server ..." ;; *) echo "`basename $0` (start|stop|restart|status)" ;; esac3 while:
适用于循环次数未知的场景,要有退出条件 语法: while CONDITION; do statement ... done 计算100以内所有正整数的和 #!/bin/bash declare -i I=1 declare -i SUM=0 while [ $I -le 100 ]; do let SUM+=$I let I++ done echo $SUM 练习:转换用户输入的字符为大写,除了quit: #!/bin/bash # read -p "Input something: " STRING while [ $STRING != 'quit' ]; do echo $STRING | tr 'a-z' 'A-Z' read -p "Input something: " STRING done 练习:每隔5秒查看hadoop用户是否登录,如果登录,显示其登录并退出;否则,显示当前时间,并说明hadoop尚未登录: #!/bin/bash # who | grep "hadoop" &> /dev/null RETVAL=$? while [ $RETVAL -ne 0 ]; do echo "`date`, hadoop is not log." sleep 5 who | grep "hadoop" &> /dev/null RETVAL=$? done echo "hadoop is logged in."while + read 组合使用:
1) 显示一个菜单给用户: d|D) show disk usages. m|M) show memory usages. s|S) show swap usages. *) quit. 2) 当用户给定选项后显示相应的内容; 扩展: 当用户选择完成,显示相应信息后,不退出;而让用户再一次选择,再次显示相应内容;除了用户使用quit; #!/bin/bash # cat << EOF d|D) show disk usages. m|M) show memory usages. s|S) show swap usages. *) quit. EOF read -p "Your choice: " CHOICE while [ $CHOICE != 'quit' ];do case $CHOICE in d|D) echo "Disk usage: " df -Ph ;; m|M) echo "Memory usage: " free -m | grep "Mem" ;; s|S) echo "Swap usage: " free -m | grep "Swap" ;; *) echo "Unknown.." ;; esac read -p "Again, your choice: " CHOICE done