kution 发表于 2018-8-28 13:26:53

shell脚本编程:条件判断if语句使用小结

  shell脚本编程,有三种控制结构分别是:顺序结构,条件判断结构,循环结构。本文将总结shell脚本中条件判断结构的使用方法。
  条件判断结构分为三种,单分支,双分支,多分支,等结构。
  单分支结构的语法如下:
  if [ expression] ;then
  statement1
  statement2
  .........
  fi
  双分支语法结构:
  if [ expression ];then
  statement1
  statement2
  .....
  else
  statement3
  statement4
  ......
  fi
  多分支语法结构:
  if [ expresion1 ];then
  statement1
  ....
  elif [ expression2 ];then
  statement2
  ......
  elif [ expression3 ];then
  statement3
  ......
  else
  statement4
  ......
  fi
  需要注意在什么时候需要使用then,以及then前面的分号是必不可少的,否则会出错。
  if 永远和fi配对
  if 或者elif 后面一定有then
  多分支条件语句实例:
  # cat test.sh
  #!/bin/bash
  read -p 'please input your file ' FILE
  #FILE=/etc/passwddd
  if [ ! -e $FILE ];then
  echo "$FILE is not exist "
  exit 3
  fi
  if [ -f $FILE ];then
  echo "$FILE is common file"
  elif [ -d $FILE ];then
  echo "$FILE is directory file"
  elif [ -x $FILE ];then
  echo "$FILE can be excuteable"
  elif [ -w $FILE ];then
  echo "$FILE can be written"
  elif [ -r $FILE ];then
  echo "$FILE can read"
  else
  echo "unkown file"
  fi

页: [1]
查看完整版本: shell脚本编程:条件判断if语句使用小结