12.2 使用结构化命令之二(if-then-else语句)

if-then-else语句

在if-then语句中,不管命令是否成功执行,你都只有一种选择。如果命令返回一个非零的状态退出码,bash shell会继续执行脚本中的下一条命令。而if-then-else语句则可以提供另一组命令。
格式

if command
then
	commands
else
	commands
fi

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

[root@CHENDAJIE if-then-else-test]# cat test1 
#!/bin/bash
# Testing the else section
#
testuser=NoSuchUser
#
if grep $testuser /etc/passwd
then
        echo "The bash files for user $testuser are:"
        ls -a /home/$testuser/.b*
        echo
else
        echo "The user $testuser does not exit on this system."
        echo
fi
[root@CHENDAJIE if-then-else-test]# chmod u+x test1 
[root@CHENDAJIE if-then-else-test]# ./test1 
The user NoSuchUser does not exit on this system.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值