shell结构化命令——if-then-else语句

本文介绍了在Bashshell脚本中如何使用if-then-else语句,当命令返回非0退出状态码时执行else部分的命令,如测试用户是否存在,以增强脚本的条件控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在if-then语句中,不管命令是否成功执行,你都只有一种选择。如果命令返回一个非0退出状态码,则bash shell会继续执行脚本中的下一条命令。在这种情况下,如果能够执行另一组命令就好了。这正是if-then-else语句的作用。

if-then-else语句在语句中提供了另外一组命令:

if command

then 

       command

else

        command

fi

当if语句中的命令返回退出状态码0时,then部分中的命令会被执行,这跟普通的if-then语句一样。当if语句中的命令返回非0退出状态码时,bash shell会执行else部分中的命令。

现在你可以复制并修改测试脚本,加入else部分:

$ cp test3.sh test4.sh
$
$ nano test4.sh
$
$ cat test4.sh
#!/bin/bash
# testing the else section
#
testuser=NoSuchUser
#
if grep $testuser /etc/passwd
then
    echo "The scropt files in the home directory of $testuser are:"
    ls /home/$testuser/*.sh
    echo
else
    echo "The user $testuser does not exist on this system."
    echo
fi
echo "We are outside the if statement"
$
$ ./test4.sh
The user NoSuchUser does not exist on this system.

We are outside the if statement

这样就友好多了。跟then部分一样,else部分可以包含多条命令。fi语句说明else部分结束。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值