shell脚本编程进阶(一)

条件判断

if语句

  1. 可以嵌套
  2. 分支
  • 单分支

      if 判断条件;then

              条件为真的分支代码

      fi

  • 双分支

      if 判断条件; then
             条件为真的分支代码
      else
             条件为假的分支代码
      fi

  • 多分支,逐条件进行判断,第一次遇为“真”条件时,执行其分支,而后结束整个if语句

      if 判断条件1; then
             条件1为真的分支代码
             elif 判断条件2; then
                     条件2为真的分支代码
             elif 判断条件3; then
                     条件3为真的分支代码
     else
            以上条件都为假的分支代码
     fi

case  

  1. 格式

      case 变量 in

      PAT1)

               分支1

     PAT2)

              分支2

    2. 对某个字符或值做判断,看它是否与某个值相匹配

    3. case支持glob风格的通配符

  • *: 任意长度任意字符
  • ?: 任意单个字符
  • []:指定范围内的任意单个字符
  • a|b: a或b

练习

先对比一下if和case

1. 编写脚本/root/bin/yesorno.sh,提示用户输入yes或no,并判断用户输入的是yes还是no,或是其它信息。

先用if来做

#!bash/bin
read -p "please input answer:" ans
if [[ $ans =~ ^[Yy]([Ee][Ss])?$ ]];then
        echo YES
elif [[ $ans =~ ^[Nn][oO]?$ ]];then
        echo NO
else echo "wrong"
fi

再来看case

#!/bin/bash
read -p ":" ans
case $ans in
[Yy]|[Yy][Ee][Ss])
        echo YES
        ;;
[Nn]|[Nn][oO])
        echo NO
        ;;
*)
        echo bad input;
esac

对于这两种条件判断, 我觉得if的适用性要更广泛;而case在判断变量是否为某些数字或是某些字符时很方便。

2. 编写脚本/root/bin/createuser.sh,实现如下功能:使用一个用户名做为参数,如果指定参数的用户存在,就显示其存在,否则就添加;显示添加的用户的id号等信息。
 

#!/bin/bash
read -p "Please input username:" username
#创建输入的用户
useradd $username &> /dev/null
#判断创建操作的返回值是否为0来,为0说明创建成功,该用户之前不存在;不为0说明创
建失败,该用户已存在
if [ $? -eq 0 ];then
    echo "$username is created" && id $username
else
    echo "The user already exists"
fi

3. 编写脚本/root/bin/filetype.sh,判断用户输入文件路径,显示其文件类型(普通,目录,链接,其它文件类型)
 

#!/bin/bash
read -p ":" a
#先判断用户输入的内容是否存在
ls $a &> /dev/null
if [ $? -eq 0 ];then  
     if [ -d "$a" ] ;then
        echo "$a is directory"
     elif [ -L "$a" ] ;then
        echo "$a is a link"
     elif [ -f "$a" ] ;then
        echo "$a is a common file"
     else
        echo "$a is other type"
     fi
else
    echo "waht you input is not exist"
    exit 1
fi

4. 编写脚本/root/bin/checkint.sh,判断用户输入的参数是否为正整数
 

#!/bin/bash
read -p "please input a digit:" num
#当然,01、001这些也可以是正整数,但是标准不同结果不同,我在这里直接剔除了01、001这种标准,采用1这样的标准
if [[ $num =~ (^[1-9][0-9]*$) ]];then
   echo "this digit is positive integer"
else
   echo "this digit is not positive integer"                                      
fi

猜你喜欢

转载自blog.csdn.net/qq_39155877/article/details/82289184