Shell 脚本实践

1. 脚本判断命令输出是否为空

(1)判断字符串为空

  if [ "$str" =  "" ] 
  if [ x"$str" = x ]
  if [ -z "$str" ] (-n 为非空)
  注意:都要代双引号,否则有些命令会报错,养成好习惯吧!  

2.输入y/n

  可以使用判断符号进行数据的判断,如检查某变量是否为空 [ -z $SHELL ],需要注意的是中括号(“[]”)内的组件必须以空格隔开。有以下脚本:

#!/bin/bash
read -p "input you choice(y/n):" choice
[ "$choice" == "y" ] || [ "$choice" == "Y" ] && echo "OK,continue" && exit 0
[ "$choice" == "n" ] || [ "$choice" == "N" ] && echo "Oh,interrupt!" && exit 0
echo "I don't know what is your choice" && exit 0
#! /bin/sh

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
exit 0

  

(3)while条件循环

和C语言类似。比如一个验证密码的脚本:

#! /bin/sh
echo "Enter password:"
read TRY
while [ "$TRY" != "secret" ]; do
  echo "Sorry, try again"
  read TRY
done
下面的例子通过算术运算控制循环的次数:

#! /bin/sh

COUNTER=1
while [ "$COUNTER" -lt 10 ]; do
  echo "Here we go again"
  COUNTER=$(($COUNTER+1))
done

(3)case 和 while 结合

#!/bin/bash
while :                                   :表示真,一直循环
do                                        要循环执行的命令
        echo -n "enter any number [1-5]:" 输入序号1-5
        read nu                            设置read的变量
        case $nu in                        进行选择,输入的要是1-5的数字
        1|2|3|4|5)
                echo "enter anumber 1 and 5" 就循环这一行,让你不停的输入1-5
                ;;
        *)                                   如果输入的不是1-5的数字
                echo -n "wrong number, continue (y/n?:)"   询问你是否继续
                read con                     设置read的变量
                case $con in                 进行选择,看是不是y|yes|Y|YES这几个
                y|yes|Y|YES)
                        continue              如果是,那么就跳过,让你重新输入,如果不是
                        ;;
                *)                             那么就执行这个break退出循环
                        break
                        ;;
                esac
        esac
done

 

  

posted @ 2015-04-12 16:44  晋心  阅读(478)  评论(0编辑  收藏  举报