linux常用命令

shell-If语句

2019-10-20  本文已影响0人  hellowenqi

一、写法

if 语句的常规表达式为:

if expression
then
  statement
if

一行的写法为

if expression; then  statement; if

二、Expression

方括号

单方括号和双括号都可以,区别

if [ 1> 0 ]; then
  echo "1 > 0"
fi
# 可以简写成这样
[ 1 > 0 ] && echo "1 > 0"    # 1 > 0

test

可以进行数字、字符串、文件的探测

a=1
if test $a -eq 1; then
 echo '$a is 1'   # 输出$a is 1
fi

b='b'
if test $b = 'b'; then
 echo '$b is b'  # 输出$b is b
fi

touch c
if test -f c; then
 echo 'c is file'  # 输出c is file
fi

函数或命令

可以如果是函数,函数的返回值是0,执行then语句。
如果是命令,可以多条,均会执行,如果最后一条的命令的返回值是0,执行then语句

function functionReturn0(){
  return 0
}

if functionReturn0; then
  echo "function return 0" # 输出function return 0
fi
if
echo 999 | grep 9
echo 999 | grep 6
then
  echo "the last command returns 0"
else
  echo "the last command returns 1"
fi
# 输出如下
# 999
# the last command returns 1

if
echo 999 | grep 6
echo 999 | grep 9
then
  echo "the last command returns 0"
else
  echo "the last command returns 1"
fi
# 输出如下
999
the last command returns 0
上一篇下一篇

猜你喜欢

热点阅读