一,for循环
#!/bin/bashfor file in $(ls /tmp/test/mytest |grep sh) //for in格式是shell for的基本格式,根js的for in类似do //循环开始你就把它当成{ echo $filedone //循环结束你就把它当成}for ((i=0;i<10;i++)) //注意是双小括号,由于受其他语言的影响,很容易搞错do echo -n $idoneecho //输出换行for i in 0 1 2 3 4 5 6 7 8 9do echo -n $idoneecho for i in "0 1 2 3 4 5 6 7 8 9" //这个根上面是有区别的,这个循环只循环了一次,双引号里面只是一个变量do echo -n $idoneexit 0
二,while循环
#!/bin/bashi=0while ((i<10))do echo $i ((i += 1))donei=0while [ $i -lt 10 ] //注意括号内侧二边的空格do echo $i let "i+=1" //加1doneexit 0
三,until循环
#!/bin/bashEND_CONDITION=enduntil [ "$var1" = "$END_CONDITION" ] //读取的变量根设定的变量相等时退出循环,不然永远循环do echo "Input variable #1 " echo "($END_CONDITION to exit)" read var1 echo "variable #1 = $var1" echodone exit 0
四,if语句
#!/bin/bashecho "Input a number #1 "read numecho "variable #1 = $num"if [ $num -lt 60 ] //注意lt前面的-,很容易忘的then echo "you are not pass"elif [ $num -lt 70 ] && [ $num -ge 60 ] //多个条件的判断then echo "pass"elif [[ $num -lt 85 && $num -ge 70 ]] //如果放在一起,要注意是双方括号,不要写成[ $num -lt 85 && $num -ge 70 ]then echo "good"elif (( $num <= 100 )) && (( $num >= 85 )) //对于有语言基础的人来说,这种写法让人觉得很舒服,不要忘了是双小括号then echo "very good"else echo "num is wrong"fi //if要有结束标签的,根XML很像,不闭合,就报错exit 0
五,case语句
#!/bin/shcase $1 in start) echo "start ok" ;; //注意一点,要注意是双分号 stop) echo "stop ok" ;; restart) echo "restart ok" ;; *) echo "no param" ;;esac //注意闭合标签exit 0[root@krlcgcms01 forif]# sh c1.sh stopstop ok