Shell脚本基础之条件判断与测试命令详解
1. 初探if - then语句
在Shell脚本编写中,我们常常会用到 if - then 语句来根据命令执行结果进行条件判断。以下是一个简单示例:
$ cat test3.sh
#!/bin/bash
# testing multiple commands in the then section
#
testuser=NoSuchUser
#
if grep $testuser /etc/passwd
then
echo "This is my first command"
echo "This is my second command"
echo "I can even put in other commands besides echo:"
ls -a /home/$testuser/.b*
fi
当执行 ./test3.sh 时,如果 grep $testuser /etc/passwd 命令返回状态码为0(即成功找到用户),则会执行 then 部分的命令;若返回非零状态码,脚本会继续执行后续命令。不过,这个脚本在用户不存在时没有给出提示,显得不够友好。
2. 深入了解if - then - else语句
为了在命令执行失败时执行另一组命令,我们可以使用 if - then - else 语句。其语法结构如下:
超级会员免费看
订阅专栏 解锁全文
644

被折叠的 条评论
为什么被折叠?



