开发手册 欢迎您!
软件开发者资料库

Linux shell脚本中的条件语句

在编写 Linux shell脚本时,可能需要从给定的两种情况中选择一种情况。则需要使用条件语句来使程序做出正确的决定并执行正确的操作。Linux shell脚本支持条件语句,用于根据不同的条件执行不同的操作。

1、if-else语句

if-else是条件判断语句,执行给定条件的一种情况,

有以下几种形式:

1)只有if的语句

只有if的条件语句是最简单的条件判断语句,如果结果值为true,则执行给定的语句。如果表达式为false,则不会执行任何语句。

语法

if [ expression ] then    当表达式为true时执行的语句fi

注意:大括号和表达式之间的空格。没有空格会产生语法错误。

例如,

#!/bin/bashfile="/home/wonhero/demo.sh"if [ -r $file ]then   echo "文件可读"fi

2)if-else语句

if-else语句能以可控的方式执行语句,如果结果值为true,则执行给定的语句。如果表达式为false,则不会执行任何语句。

语法

if [ expression ]then   当表达式为true时执行的语句else   如果表达式为false,将执行的语句fi

例如,

#!/bin/bashfile="/home/wonhero/demo.sh"if [ -r $file ]then   echo "文件可读"else   echo "文件不可读"fi

3)if-elif-else语句

if-elif-else语句只可以支持多个条件,每个if都是前一条语句的else子句的一部分。这里的语句是根据if条件执行的,如果没有一个条件为真,则执行else块。

语法

if [ expression1 ]then   如果expression1为true,将执行的语句elif [ expression2 ]then   如果expression2为true,将执行的语句elif [ expression3 ]then   如果expression3为true,将执行的语句else   在上面表达式条件都为false时执行的语句fi

例如,

#!/bin/bashif [[ $1 = 'tomcat' ]];then  echo "Input is tomcat"elif [[ $1 = 'redis' ]] || [[ $1 = 'zookeeper' ]];then  echo "Input is $1"else  echo "Input Is Error."fi

2、case-esac

使用if-elif语句有多个判断条件表达式,当所有分支都依赖于单个变量的值时。可以尝试使用case-esac语句,比重复的if-elif语句更简单。case-esac语句的基本语法是给出一个表达式并根据表达式的值执行几个不同的语句。解释器根据表达式的值判断每个 case,直到找到匹配条件。如果没有匹配条件,将使用默认条件。

语法,

case word in   pattern1)      如果满足pattern1,将执行的语句      ;;   pattern2)      如果满足pattern2,将执行的语句      ;;   pattern3)      如果满足pattern3,将执行的语句      ;;   *)     执行的默认条件     ;;esac

例如,

#!/bin/bashoption="${1}"case ${option} in   -f) FILE="${2}"      echo "File name is $FILE"      ;;   -d) DIR="${2}"      echo "Dir name is $DIR"      ;;   *)       echo "`basename ${0}`:usage: [-f file] | [-d directory]"      exit 1 # Command to come out of the program with status 1      ;;esac

输出:

$./test.shtest.sh: usage: [ -f filename ] | [ -d directory ]$ ./test.sh -f wonhero.pyFile name is wonhero.py$ ./test.sh -d linuxDir name is linux