shell类似与try catch的功能 ,并列举十个案例
时间: 2024-05-02 19:23:30 浏览: 112
shell的具体实例
Shell脚本中使用的语句是if、then、elif、else和fi,可以用来实现类似try-catch的功能。下面是十个案例:
1. 判断文件是否存在,存在则输出文件大小,否则输出错误信息。
```
if [ -f filename ]; then
echo "File size: $(du -h filename)"
else
echo "File not found"
fi
```
2. 判断命令是否执行成功,成功则输出成功信息,否则输出错误信息。
```
if command; then
echo "Command executed successfully"
else
echo "Command failed"
fi
```
3. 判断目录是否存在,存在则输出目录中文件数量,否则输出错误信息。
```
if [ -d directory ]; then
echo "Number of files: $(ls directory | wc -l)"
else
echo "Directory not found"
fi
```
4. 判断变量是否为空,为空则输出错误信息,否则输出变量值。
```
if [ -z "$variable" ]; then
echo "Variable is empty"
else
echo "Variable value: $variable"
fi
```
5. 判断命令执行结果是否包含期望的字符串,包含则输出成功信息,否则输出错误信息。
```
if command | grep -q "expected string"; then
echo "Command executed successfully"
else
echo "Command failed"
fi
```
6. 判断命令执行结果是否等于期望的字符串,相等则输出成功信息,否则输出错误信息。
```
if [ "$(command)" = "expected string" ]; then
echo "Command executed successfully"
else
echo "Command failed"
fi
```
7. 判断用户是否拥有权限执行命令,有权限则执行命令并输出成功信息,否则输出错误信息。
```
if [ "$(id -u)" = "0" ]; then
command
echo "Command executed successfully"
else
echo "Permission denied"
fi
```
8. 判断脚本是否以root用户身份执行,是则执行命令并输出成功信息,否则输出错误信息。
```
if [ "$(id -u)" = "0" ]; then
command
echo "Command executed successfully"
else
echo "Script must be run as root"
fi
```
9. 判断命令执行结果是否为数字,是则输出结果,否则输出错误信息。
```
result="$(command)"
if [ "$result" -eq "$result" ] 2>/dev/null; then
echo "Result: $result"
else
echo "Command failed"
fi
```
10. 判断命令执行结果是否为非零值,是则输出错误信息,否则输出成功信息。
```
if command; then
echo "Command executed successfully"
else
echo "Command failed"
exit 1
fi
阅读全文