[Linux] 结构化命令 if
语法结构如下:
1. if-then语句
# if-then语句 if command #根据conmmand的退出状态码,选择执行语句 then commands fi e.g. #!usr/bin/bash testuser=rich if grep $testuser /etc/passwd then echo The bash files for user $testuser are: ls -a /home/$testuser/ fi
2. if-then-else语句
1 #!usr/bin/bash 2 if command #根据conmmand的退出状态码,选择执行语句 3 then 4 commands 5 else 6 commands 7 fi
3. 嵌套if(elif)
1 #!usr/bin/bash 2 if command 3 then 4 commands 5 elif command 6 then 7 commands 8 elif command 9 then 10 commands 11 else 12 commands 13 fi
4. test命令(单测试条件)
1 # 主要有3类测试条件 2 * 数值比较: -eq; -ge; -gt; -le; -lt; -ne. 3 * 字符串比较:=; !=; \<; \>; -n; -z. 4 * 文件比较:-d; -e; -f; -r; -s; -w; -x; -O; -G; -nt; -ot. 5 6 #usr/bin/bash 7 if test condition 8 then 9 commands 10 fi 11 12 #!usr/bin/bash 13 if [ condition ] # condition前后又空格 14 then 15 commands 16 fi
5. 复合条件测试
1 # AND测试:必须同时满足两个条件(真) 2 if [ condition1] && [ condition2 ] 3 then 4 commands 5 fi 6 7 8 #OR测试:满足任何一个条件(任一为真) 9 if [ conditon1 ] || [ condition2 ] 10 then 11 commands 12 fi
6. if-then高级特性
1 # 双圆括号:用于数学表达式 2 (( expression )) 3 # 常用表达式:val++; val--; ++val; --val; !(逻辑求反); ~(位求反); **; <<(位左移); >>(位右移); &位布尔‘和’及‘或’; |; 逻辑‘和’及‘或’:&&; ||; 4 if (( expression )) 5 then 6 commands 7 (( expression )) 8 fi 9 10 # 双方括号:用于字符串表达式(e.g. 正则表达式) 11 [[ expression ]] 12 13 if [[ expression ]] 14 then 15 commands 16 fi
7. case命令
1 # 将指定的变量同不同的模式进行比较 2 3 4 case variable in 5 pattern1 | pattern2) 6 commands1;; 7 pattern3) 8 commands2;; 9 *) 10 commands3;; 11 esac