shell基础(七)-条件语句,shell基础条件语句


条件语句在编写脚本经常遇到;用于处理逻辑问题。


 一 IF 语句

if 语句通过关系运算符判断表达式的真假来决定执行哪个分支。Shell 有三种 if ... else 语句:
if ... fi 语句;
if ... else ... fi 语句;
if ... elif ... else ... fi 语句。

例如: 就拿a=10;b=20来举例

  >1. if ... fi 语句
    : if01.sh
     #!/bin/sh
     a=10
     b=20
     if [ $a -lt $b ];then             #$a小于$b
      echo "10 is less then 20"
     fi
   >2.if ... else ... fi 语句
     :if02.sh
     #!/bin/sh
     a=10
     b=20
     if [ $a -lt $b ];then
       echo "10 is less then 20"
     else
       echo "10 is not less then 20" 
     fi
   >3.if ... elif ... else ... fi 语句
    :if03.sh
     #!/bin/sh
     a=10
     b=20
     if [ $a -lt $b ];then
      echo "10 is less then 20"  
     elif [ $a -eq $b ];then
      echo "10 is equal to 20"
     else
      echo "10 is not less then 20"   #我没找到好点的编辑器,我是用ue
     fi

  二 case 语句

#case 语句匹配一个值或一个模式,如果匹配成功,执行相匹配的命令。语法格式:
  case 值in
   模式1)
   命令1
    . . .
    ;;
  模式2)
   命令2
    . . .
    ;;
  esac

case工作方式如上所示。取值后面必须为关键字 in,每一模式必须以右括号结束。取值可以为变量或常数。匹配发现取值符合某一模式后,其间所有命令开始执行直至 ;;。;; 与其他语言中的 break 类似,意思是跳到整个 case 语句的最后。
取值将检测匹配的每一个模式。一旦模式匹配,则执行完匹配模式相应命令后不再继续其他模式。
如果无一匹配模式,使用星号 * 捕获该值,再执行后面的命令

下面的脚本提示输入1到4,与每一种模式进行匹配:

case01.sh
 #!/bin/sh
 read -n1 -p "please input your number: " num
 case $num in 
 1)
 echo "you select 1"
 ;;
 2)
 echo "you select 2"
 ;;
 3)
 echo "you select 3"
 ;;
 4)
 echo "you select 4"
 ;;
 *)
 echo "you select other"
 ;;
 esac

 


 


shell脚本中的if中多条件语句怎写

if [ $a = "aa" -a $b = "bb" ] || [$c = "cc" -a $d = "dd" ];
then
echo "success"
fi

是这个意思吗
 

linux shell 条件语句

if [[ "$num1" -ne 0 && "$num3" -ne 0 ]]
 

相关内容