Linux Shell - if 语句和判断表达式

1. Introduction to if

if 后面是判断条件,elif 是主判断条件不成立时的其它判断条件,else 则是所有条件都不成立时要执行的语句。

1.1. if 结构

末尾的 fiif 倒过来拼写。

ifthen 写在同一行时,需要分号分隔,分号是 bash 的命令分隔符。ifthen 可以写成两行,此时不需要分号。

if condition; then
    command1
    command2
    ...
    commandn
fi

相同

if condition
then
    command1 
    command2
    ...
    commandn
fi

相同

if condition
then
    commands
fi

true 表示成功,false 表示失败。if true 意味着命令总是会执行,if false 意味着命令永远不会执行。

if true
then
    echo 'yongqiang'
fi

if false
then
    echo 'yongqiang'
fi

The most compact syntax of the if command is:

if TEST-COMMANDS; then CONSEQUENT-COMMANDS; fi

The TEST-COMMAND list is executed, and if its return status is zero, the CONSEQUENT-COMMANDS list is executed. The return status is the exit status of the last command executed, or zero if no condition tested true.

(base) yongqiang@yongqiang:~$ if true; then echo 'yongqiang'; fi
yongqiang
(base) yongqiang@yongqiang:~$
(base) yongqiang@yongqiang:~$ if false; then echo 'yongqiang'; fi
(base) yongqiang@yongqiang:~$

if 关键字后面如果是一条命令,该命令执行成功 (返回值 0),则意味着判断条件成立,否则表示不成立。下面命令中,if 后面是一条命令 echo 'name'。该命令会执行,如果返回值是 0,则执行 then 的部分。

(base) yongqiang@yongqiang:~$ if echo 'name'; then echo 'yongqiang'; fi
name
yongqiang
(base) yongqiang@yongqiang:~$

if 后面可以跟任意数量的命令。所有命令都会执行,判断真伪只看最后一个命令,即使前面所有命令都失败,只要最后一个命令返回 0,就会执行 then 的部分。if 后面有两条命令 false; true;,第二条命令 true; 决定 then 的部分会执行。

(base) yongqiang@yongqiang:~$ if false; true; then echo 'yongqiang'; fi
yongqiang
(base) yongqiang@yongqiang:~$

1.2. if else 结构

if condition; then
    commands
else
    commands
fi

相同

if condition
then
    commands
else
    commands
fi

1.3. if elif else 结构

if condition1; then
    commands
elif condition2; then    
    commands
else
    commands
fi

相同

if condition1
then
    commands
elif condition2
then    
    commands
else
    commands
fi

可以有多个 elif

if condition1; then
    commands
elif condition2; then
    commands
elif condition3; then
    commands
else
    commands
fi

2. 判断表达式

if 后面跟的是一个命令。这个命令可以是 test 命令,也可以是其他命令。命令的返回值为 0 表示判断成立,否则表示不成立。这些命令是为了得到返回值,可以视为表达式。

2.1. Primary expressions

文件判断

Primary	                     Meaning
[ -a FILE ]	                 True if FILE exists. (如果 FILE 存在,则为 true。)
[ -b FILE ]	                 True if FILE exists and is a block-special file. (如果 FILE 存在并且是一个块 (设备) 文件,则为 true。)
[ -c FILE ]	                 True if FILE exists and is a character-special file. (如果 FILE 存在并且是一个字符 (设备) 文件,则为 true。)
[ -d FILE ]	                 True if FILE exists and is a directory. (如果 FILE 存在并且是一个目录,则为 true。)
[ -e FILE ]	                 True if FILE exists. (如果 FILE 存在,则为 true。)
[ -f FILE ]	                 True if FILE exists and is a regular file. (如果 FILE 存在并且是一个普通文件,则为 true。)
[ -g FILE ]	                 True if FILE exists and its SGID bit is set. (如果 FILE 存在并且设置了 SGID 位,则为 true。)
[ -h FILE ]	                 True if FILE exists and is a symbolic link. (如果 FILE 存在并且是符号链接,则为 true。)
[ -k FILE ]	                 True if FILE exists and its sticky bit is set. (如果 FILE 存在并且设置了它的 sticky bit,则为 true。)
[ -p FILE ]	                 True if FILE exists and is a named pipe (FIFO). (如果 FILE 存在并且是一个命名管道,则为 true。)
[ -r FILE ]	                 True if FILE exists and is readable. (如果 FILE 存在并且可读 (当前用户有可读权限),则为 true。)
[ -s FILE ]	                 True if FILE exists and has a size greater than zero. (如果 FILE 存在且其长度大于零,则为 true。)
[ -t FD ]	                 True if file descriptor FD is open and refers to a terminal. (如果 FD 是一个文件描述符,并且重定向到终端,则为 true。这可以用来判断是否重定向了标准输入/输出/错误。)
[ -u FILE ]	                 True if FILE exists and its SUID (set user ID) bit is set. (如果 FILE 存在并且设置了 SUID (set user ID) 位,则为 true。)
[ -w FILE ]	                 True if FILE exists and is writable. (如果 FILE 存在并且可写 (当前用户拥有可写权限),则为 true。)
[ -x FILE ]	                 True if FILE exists and is executable. (如果 FILE 存在并且可执行 (当前用户有执行/搜索权限),则为 true。)
[ -O FILE ]	                 True if FILE exists and is owned by the effective user ID. (如果 FILE 存在并且属于有效的 user ID,则为 true。)
[ -G FILE ]	                 True if FILE exists and is owned by the effective group ID. (如果 FILE 存在并且属于有效的 group ID,则为 true。)
[ -L FILE ]	                 True if FILE exists and is a symbolic link. (如果 FILE 存在并且是一个符号链接,则为 true。)
[ -N FILE ]	                 True if FILE exists and has been modified since it was last read. (如果 FILE 存在并且自上次读取后已被修改,则为 true。)
[ -S FILE ]	                 True if FILE exists and is a socket. (如果 FILE 存在且是一个 socket,则为 true。)
[ FILE1 -nt FILE2 ]	         True if FILE1 has been changed more recently than FILE2, or if FILE1 exists and FILE2 does not. (如果 FILE1 比 FILE2 的更新时间更近,或者 FILE1 存在而 FILE2 不存在,则为 true。)
[ FILE1 -ot FILE2 ]	         True if FILE1 is older than FILE2, or is FILE2 exists and FILE1 does not. (如果 FILE1 比 FILE2 的更新时间更旧,或者 FILE2 存在而 FILE1 不存在,则为 true。)
[ FILE1 -ef FILE2 ]          True if FILE1 and FILE2 refer to the same device and inode numbers. (如果 FILE1 and FILE2 引用相同的设备和 inode 编号,则为 true。)
[ -o OPTIONNAME ]            True if shell option "OPTIONNAME" is enabled.

字符串判断

Primary	                     Meaning
[ -z STRING ]                True if the length of "STRING" is zero. (如果字符串 "STRING" 的长度为零,则判断为真。)
[ -n STRING ] or [ STRING ]  True if the length of "STRING" is non-zero. (如果字符串 "STRING" 的长度大于零,则判断为真。)
[ STRING1 == STRING2 ]       True if the strings are equal. "=" may be used instead of "==" for strict POSIX compliance. (如果 "STRING1" 和 "STRING2" 相同,则判断为真。)
[ STRING1 != STRING2 ]       True if the strings are not equal. (如果 "STRING1" 和 "STRING2" 不相同,则判断为真。)
[ STRING1 < STRING2 ]        True if "STRING1" sorts before "STRING2" lexicographically in the current locale. (如果按照字典顺序 "STRING1" 排列在 "STRING2" 之前,则判断为真。)
[ STRING1 > STRING2 ]        True if "STRING1" sorts after "STRING2" lexicographically in the current locale. (如果按照字典顺序 "STRING1" 排列在 "STRING2" 之后,则判断为真。)
locale [ləʊˈkɑːl]:n. 场所,现场,发生地点
lexicographic:adj. 词典式的,词典编辑上的

整数判断

Primary	                     Meaning
[ ARG1 OP ARG2 ]	         "OP" is one of -eq, -ne, -lt, -le, -gt or -ge. These arithmetic binary operators return true if "ARG1" is equal to, not equal to, less than, less than or equal to, greater than, or greater than or equal to "ARG2", respectively. "ARG1" and "ARG2" are integers.

[ integer1 -eq integer2 ]    如果 integer1 等于 integer2,则为 true。
[ integer1 -ne integer2 ]    如果 integer1 不等于 integer2,则为 true。
[ integer1 -le integer2 ]    如果 integer1 小于或等于 integer2,则为 true。
[ integer1 -lt integer2 ]    如果 integer1 小于 integer2,则为 true。
[ integer1 -ge integer2 ]    如果 integer1 大于或等于 integer2,则为 true。
[ integer1 -gt integer2 ]    如果 integer1 大于 integer2,则为 true。
arithmetic [əˈrɪθmətɪk]:n. 算术,演算,计算,数据统计 adj. 算术的,运算的

2.2. Combining expressions

The [ (or test) built-in evaluates conditional expressions using a set of rules based on the number of arguments. Just like the if is closed with fi, the opening square bracket should be closed after the conditions have been listed.
[ (or test) 内置使用一组基于参数数量的规则来评估条件表达式。就像 iffi 结束一样,左方括号应该在列出条件后关闭。

Operation	        Effect
[ ! EXPR ]	        True if EXPR is false.
[ ( EXPR ) ]	    Returns the value of EXPR. This may be used to override the normal precedence of operators.
[ EXPR1 -a EXPR2 ]	True if both EXPR1 and EXPR2 are true.
[ EXPR1 -o EXPR2 ]	True if either EXPR1 or EXPR2 is true.
precedence [ˈpresɪdəns]:n. 优先,优先权

References

[1] Yongqiang Cheng, https://yongqiang.blog.csdn.net/
[2] Bash Guide for Beginners, https://tldp.org/LDP/Bash-Beginners-Guide/html/index.html
[3] Chapter 7. Conditional statements, https://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html

  • 6
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 如果语句shell 脚本中的一种判断语句,允许在特定条件为真时执行一组命令,并在特定条件为假时执行另一组命令。语法格式如下: ``` if [ condition ]; then commands1 else commands2 fi ``` 其中 `condition` 是一个测试命令,如果其返回值为真,则执行命令 `commands1`,否则执行命令 `commands2`。 ### 回答2: if语句shell编程中最基本的控制结构之一,它允许根据条件执行不同的命令或语句块。if语句的基本语法如下: ``` if condition then command1 command2 ... else command3 command4 ... fi ``` 其中,condition是一个测试条件,可以使用比较操作符(例如-eq、-ne、-lt、-gt、-le、-ge)、逻辑操作符(例如&&和||)、以及test命令来测试。如果condition为真,那么if语句中then到else之间的部分会被执行,否则执行else到fi之间的部分(如果有的话)。注意,if、then、else和fi这些关键字都需要用空格分开。 下面是一个简单的例子: ``` #!/bin/bash FILE="example.txt" if [ -e "$FILE" ] then echo "$FILE exists." else echo "$FILE does not exist." fi ``` 这个脚本会测试example.txt文件是否存在。如果存在,会输出“example.txt exists.”,否则输出“example.txt does not exist.”。 除了基本语法,if语句还可以使用嵌套的形式来实现更复杂的控制结构。例如: ``` if [ "$VAR1" = "value1" ] then if [ "$VAR2" -lt "10" ] then echo "VAR1 is value1 and VAR2 is less than 10." else echo "VAR1 is value1 but VAR2 is not less than 10." fi else echo "VAR1 is not value1." fi ``` 这个脚本会先测试VAR1变量是否等于value1,如果是,再测试VAR2是否小于10。如果VAR1不是value1,就直接输出“VAR1 is not value1.”。 总之,if语句shell编程中非常基本的控制结构,可以根据条件执行不同的命令和语句块。学习if语句的基本语法和使用方法,对于编写复杂的shell脚本非常有帮助。 ### 回答3: 在 Linux shell 中,if 语句是一种用于控制流程的条件语句,通常用于判断某个表达式是否成立以执行特定的代码块。if 语句的基本格式为: ``` if [ 条件表达式 ]; then # 条件成立时执行的代码块 else # 条件不成立时执行的代码块 fi ``` 其中,条件表达式一般是一个命令或变量判断的逻辑表达式,如 `if [ $a -eq 1 ]`,表示当变量 `$a` 等于 1 时条件成立;`if [ -f file.txt ]`,表示当当前目录下有名为 file.txt 的文件时条件成立。如果条件成立,则执行 then 后面的代码块,否则执行 else 后面的代码块。 还可以用 elif 关键字设置多个条件分支,格式如下: ``` if [ 条件表达式1 ]; then # 条件1成立执行的代码块 elif [ 条件表达式2 ]; then # 条件2成立执行的代码块 else # 以上条件都不成立则执行的代码块 fi ``` 除了直接在 if 语句行中写条件表达式外,我们还可以采用变量或命令的方式来构造条件表达式,常用的有: - 命令的条件控制: ``` if command; then # command 命令返回 0 时执行的代码块 else # command 命令返回非 0 值时执行的代码块 fi ``` - 变量的条件控制: ``` if [ -n "$var" ]; then # 判断变量是否非空 # 变量不为空时执行的代码块 fi ``` if 语句中还有一些比较特殊的用法,例如: - 判断文件是否存在: ``` if [ -e file ]; then # -e 表示判断文件是否存在 # 文件存在时执行的代码块 fi ``` - 检查字符串是否包含另一个字符串: ``` if [[ "$str" == *substr* ]]; then # 包含子串时执行的代码块 fi ``` 总之,if 语句Linux shell 编程中最常用的控制流程的条件语句,掌握好 if 语句的写法和用法,可以让你更加灵活地处理各种情况下的程序逻辑问题,提高编程效率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Yongqiang Cheng

梦想不是浮躁,而是沉淀和积累。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值