Shell循环控制语句

1. if语句

  1. 输入字符串,如果是yes则打印正确,不是yes也是no的话打印不可识别,返回状态1,正常结束后返回0
  2. if then elif else fi
#!/bin/sh
 echo '请输入yes或no'
     read x
 if [ $x = 'yes' ]; then
     echo 正确
 elif [ $x = 'no' ]; then
     echo 错误
 else
     echo 不可识别
 exit 1;
 fi
 exit 0

单行if语句

if [ $x = 'yes' ]; then echo 正确; elif [ $x = 'no' ]; then echo 错误; else echo 不可识别; exit 1; fi

2. for语句

  • 循环依序将a b c放入变量ABC中,打印变量ABC,输出结果为a b c
  • for do done
for ABC in a b c; do
     echo $ABC
 done

单行for语句

for ABC in a b c;do echo $ABC; done

3. while语句

  • 当变量s小于等于100时进入循环,打印变量s,s=s+2返回循环
  • while do done
s=2
     while [ $s -le 100 ]; do
 echo $s
     s=$(( $s + 2 ))
 done

单行while语句

while [ $s -le 100 ]; do echo $s; s=$(( $s + 2 )); done

4. until语句

与while用法完全相反,条件为false时始终执行

5. case语句

  • 键盘接收一个变量ch,如果ch为AEIOUaeiou任意一个字符,则打印是元音字母,否则打印不是元音字母
  • case esac
#!/bin/sh
 echo '请输入一个字母'
     read ch
 case $ch in
     [AEIOU]|[aeiou])
 echo '是元音字母'
 echo $ch ;;
     *)
 echo '不是元音字母'
 echo $ch
     exit 1;;
 esac
     exit 0

6. continue和break

shell脚本支持continue跳出当次循环和break跳出全部循环

猜你喜欢

转载自blog.csdn.net/wxfghy/article/details/80597299