shell 的使用(其二 分支 循环语句)

一,shell 判断语句:
1,Shell中用if、then、elif、else、fi(if 语句的结束)这几条命令实现分支控制
#! /bin/sh

# : 表示空命令 永远为真的意思
if :;then echo "alwsys true";fi
echo "Is it morning? Please answer yes or no."
# 此处是读取键盘操作!讲键盘输入保存到变量之中
read YES_OR_NO
if [ "$YES_OR_NO" = "yes" ]; then
  echo "Good morning!"
elif [ "$YES_OR_NO" = "no" ]; then
  # 加不加" " 是等价的
  echo Good afternoon!
else
  echo "Sorry, $YES_OR_NO not recognized. Enter yes or no."
  exit 1
fi
# 设置状态为 0,也就是 echo $? 为0
exit 0
# 如果 输入了 no echo $? 不在为 1 因为执行下面语句更改为 0
if :;then echo "alwsys true";fi
第二种 判断语句写法:
1,Shell还提供了&&和||语法,
2,&&相当于“if...then...”,而||相当于“if not...then...”
test "$(whoami)" != 'root' && (echo you are using a non-privileged account; exit 1)

test "$(whoami)" != 'admin' || (echo you are not using a non-privileged account; exit 1)
二,shell case 语句的使用:
1,相当于 C语言的switch/case语句,esac表示case语句块的结束
2,很多服务的启动脚本是使用的 case 实例
#! /bin/sh

echo "Is it morning? Please answer yes or no."
# 读取键盘输入 保存到 YES_OR_NO 变量之中
read YES_OR_NO
case "$YES_OR_NO" in
yes|y|Yes|YES)    # 语法格式是 半括号
  echo "Good Morning!";; # ;; 表示 break 的意思 [nN]* 正则匹配
[nN]*)  
  echo "Good Afternoon!";;
*)
  echo "Sorry, $YES_OR_NO not recognized. Enter yes or no."
  exit 1;;
esac
exit 0
执行 reboot -f 命令时 
在/etc/init.d/reboot 启动脚本之中是这么使用的!
do_stop () {
        # Message should end with a newline since kFreeBSD may
        # print more stuff (see #323749)
        log_action_msg "Will now restart"
        reboot -d -f -i
}
# 捕获键盘输入
case "$1" in
  start)
        # No-op
        ;;
  restart|reload|force-reload)
        echo "Error: argument '$1' not supported" >&2
        exit 3
        ;;
  stop)
        do_stop
        ;;
  status)
        exit 0
        ;;
  *)
        echo "Usage: $0 start|stop" >&2
        exit 3
        ;;
esac
for 与 while 循环的使用 for--do--done  while--do--done
#! /bin/sh
# for 循环的使用!
for FRUIT in apple banana pear; do
  echo "I like $FRUIT"
done

# 密码输入三次就退出!
echo "Enter password:"
read TRY
num=1
while [ "$TRY" != "secret" ]; do
  echo "Sorry, try again"
  num=$(($num+1))
  if [ $num -gt 3 ];then
     # \n 表示换行
     echo '\nYou can only try three times at most.'
     break
  fi
  read TRY
done

 

posted @ 2018-10-13 14:30  十七楼的羊  阅读(201)  评论(0编辑  收藏  举报