程序员

Linux Shell之if语法和常用场景

2020-05-26  本文已影响0人  唯米天空

1. 语法

1.1. 标准语法

if 条件
then
    command1
else
    command2
fi

如果没写fi,报错信息:

test.sh: line 14: syntax error: unexpected end of fi

1.2. 简练语法

条件 && 命令
条件 || 命令

比如

[ -f "/etc/shadow" ] && echo "This computer uses shadow passwors"
&& 如果是“前面”,则“后面”
[ -f /var/run/dhcpd.pid ] && rm /var/run/dhcpd.pid    检查 文件是否存在,如果存在就删掉
   ||   如果不是“前面”,则后面
[ -f /usr/sbin/dhcpd ] || exit 0    检验文件是否存在,如果存在就退出

当条件返回为true,这里的true的意思是条件返回为0.返回为0,跟其他语言语法不一样,正好相反。

2. 三种 “条件” 方式

2.1. 方式一

if
    command
then
    command1
else
    command2
fi

if command 等价于 command+if $?

$?表示上一条命令返回结果

[xrepos@repos wdog]$ hahaha
-bash: hahaha: command not found
[xrepos@repos wdog]$ echo $?
127
[xrepos@repos wdog]$ ls
[xrepos@repos wdog]$ echo $?
0
if
 函数
then

命令执行成功,等于返回0 (比如grep ,找到匹配)
执行失败,返回非0 (grep,没找到匹配)

2.2. 方式二

if [ expression_r_r_r  ]
then

表达式结果为真,则返回0,if把0值引向then

2.3. 方式三

if test expression_r_r_r
then

表达式结果为假,则返回非0,if把非0值引向then

3. 条件表达式(重点)

3.1. 基本

文件表达式
if [ -f  file ]    如果文件存在
if [ -d ...   ]    如果目录存在
if [ -s file  ]    如果文件存在且非空 
if [ -r file  ]    如果文件存在且可读
if [ -w file  ]    如果文件存在且可写
if [ -x file  ]    如果文件存在且可执行   
整数变量表达式
if [ int1 -eq int2 ]    如果int1等于int2   
if [ int1 -ne int2 ]    如果不等于    
if [ int1 -ge int2 ]       如果>=
if [ int1 -gt int2 ]       如果>
if [ int1 -le int2 ]       如果<=
if [ int1 -lt int2 ]       如果<
   
   字符串变量表达式
If  [ $a = $b ]                 如果string1等于string2
                                字符串允许使用赋值号做等号
if  [ $string1 !=  $string2 ]   如果string1不等于string2       
if  [ -n $string  ]             如果string 非空(非0),返回0(true)  
if  [ -z $string  ]             如果string 为空
if  [ $sting ]                  如果string 非空,返回0 (和-n类似)

Tips:

if [ $a = 123 ] ; then
echo equal123
fi

(等号做赋值号时正好相反,两边不能有空格)

3.2. 逻辑组合

if [ ! -d $num ] 
#如果不存在目录$num
if [ 表达式1  –a  表达式2 ]
if [ 表达式1  –o 表达式2 ]

参考链接

http://blog.sina.com.cn/s/blog_64e166580100vwk2.html


上一篇 下一篇

猜你喜欢

热点阅读