Shell 流程控制 - if 条件结构
简介
-
主要的关键字有:" if " 、" then " 、" elif " 、" else " 、" fi " 。
- " then " :存在于 " if " 或 " elif " 后," else " 后则不需要,后面为满足条件时要执行的内容。
- " fi " :" if " 结构结束的标志。
-
搭配 " [ ] " 使用,使用时 " [ ] " 与 其中的条件,都要用空格隔开。
-
语法格式
if condition1 then command1 elif condition2 then command2 else commandN fi
-
写成一行(适用于终端命令提示符):
if [ $(ps -ef | grep -c "ssh") -gt 1 ]; then echo "true"; fi
参考文章
- 官方文档:https://www.gnu.org/software/bash/manual/bash.html#Conditional-Constructs
- 参考文章:https://www.runoob.com/linux/linux-shell-process-control.html
示例
- 文件或目录的判断
[root@ if]# vim test.sh
[root@ if]# cat test.sh
#!/bin/bash
if [ -f $1 ]
then
echo "$1 是文件。"
elif [ -d $1 ]
then
echo "$1 是目录。"
else
echo "不在判断范围内。"
fi
[root@ if]# sh test.sh /root/
/root/ 是目录。
[root@ if]# sh test.sh /root/.bashrc
/root/.bashrc 是文件。
[root@ if]# sh test.sh /dev/null
不在判断范围内。
[root@ if]#