条件判断

if

语法

  • 语法一
if 判断条件; then
   条件为真的分支代码,也是需要执行的命令。
fi
  • 语法二
if condition
then
    commands
fi

范例

使用 if 语句判断 /tmp/a.txt 是否存在,如果不存在,就创建这个文件

## 方法一
if [ ! -f /tmp/a.txt ]; then
  touch /tmp/a.txt
fi


## 方法二
if [ ! -f /tmp/a.txt ]
then
  touch /tmp/a.txt
fi


## 方法三
if [ ! -f /tmp/a.txt ]; then touch /tmp/a.txt ; fi
  • 其他方法:[ ! -f /tmp/a.txt ] && touch /tmp/a.txt

if-else

语法

  • 语法一
if 判断条件; then
 条件为真的分支代码
else
 条件为假的分支代码
fi
  • 语法二
## 如果condition成立,执行commands1,否则执行commands2。
if condition
then
    commands1
else
    commands2
fi

范例

使用 if 语句判断 /tmp/a.txt 是否存在,如果不存在,就创建这个文件。如果存在,就打印文件已存在的话

## 方法一
if [ ! -f /tmp/a.txt ]; then
  touch /tmp/a.txt
else
  echo "文件已存在"
fi


## 方法二
if [ ! -f /tmp/a.txt ]
then
  touch /tmp/a.txt
else
  echo "文件已存在"
fi


## 方法三
if [ ! -f /tmp/a.txt ]; then touch /tmp/a.txt ; else echo "文件已存在" ; fi

if-elif-else

  • 多个条件时,逐个条件进行判断,第一次遇为“真”条件时,执行其分支,而后结束整个if语句
## 语法一
if 判断条件1; then
 条件1为真的分支代码
elif 判断条件2; then
 条件2为真的分支代码
elif 判断条件3; then
 条件3为真的分支代码
...
else
 以上条件都为假的分支代码
fi
## 如果 condition1 成立,执行`commands1`;如果`condition2`成立,执行`commands2`;否则执行`commands3`。
if condition1
then
    commands1
elif condition2
then
    commands2
else
    commands3
fi

case

语法

case WORD in [PATTERN [| PATTERN]...) COMMANDS ;;]... esac
case 变量引用 in
PAT1)
 分支1
 ;;
PAT2)
 分支2
 ;;
...
*)
 默认分支
 ;;
esac

其中,expression是需要匹配的表达式,pattern1pattern2等是不同的模式,commands1commands2等是对应的命令。如果没有任何一个模式匹配成功,则执行default commands

case expression in
    pattern1)
        commands1;;
    pattern2)
        commands2;;
    ...
    *)
        default commands;;
esac

范例:

#!/bin/bash
cat <<EOF
1) Issue certificate
2) Revoke certificate
3) exit
EOF

read -p "please enter a number (1-3): " NUM

case ${NUM} in
1)
    echo issue
    ;;
2)
    echo revoke
    ;;
*)
    echo syntax error exit && exit 3
esac

case 支持通配符

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

范例:

#!/bin/bash
read -p "Do you agree(yes/no)? " INPUT
case $INPUT in
[yY]|[Yy][Ee][Ss])
    echo "You input is YES"
   ;;
[Nn]|[Nn][Oo])
    echo "You input is NO"
   ;;
*)
    echo "Input fales,please input yes or no!"                                   
                             
esac