Linux if语句常用shell脚本
时间: 2023-10-21 18:19:23 浏览: 89
1. 判断文件是否存在
```bash
if [ -f /path/to/file ]; then
echo "File exists"
else
echo "File does not exist"
fi
```
2. 判断目录是否存在
```bash
if [ -d /path/to/dir ]; then
echo "Directory exists"
else
echo "Directory does not exist"
fi
```
3. 判断字符串是否为空
```bash
if [ -z "$string" ]; then
echo "String is empty"
else
echo "String is not empty"
fi
```
4. 判断两个字符串是否相等
```bash
if [ "$str1" = "$str2" ]; then
echo "Strings are equal"
else
echo "Strings are not equal"
fi
```
5. 判断数字大小
```bash
if [ $num1 -gt $num2 ]; then
echo "$num1 is greater than $num2"
else
echo "$num1 is less than or equal to $num2"
fi
```
6. 判断命令执行结果
```bash
if command; then
echo "Command succeeded"
else
echo "Command failed"
fi
```
7. 嵌套if语句
```bash
if [ condition1 ]; then
if [ condition2 ]; then
#statements
fi
fi
```
8. 判断脚本参数个数
```bash
if [ $# -eq 0 ]; then
echo "No arguments provided"
else
echo "Number of arguments: $#"
fi
```
9. 判断用户是否有执行脚本的权限
```bash
if [ "$(whoami)" != "root" ]; then
echo "You do not have permission to run this script"
exit 1
fi
```
10. 判断系统类型
```bash
if [ "$(uname)" == "Linux" ]; then
echo "This is a Linux system"
elif [ "$(uname)" == "Darwin" ]; then
echo "This is a macOS system"
else
echo "Unknown system type"
fi
```
阅读全文