当前位置: 代码网 > 服务器>服务器>Linux > shell结构化命令if-then-else语句

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

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

在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部分中的命令。

shell脚本首先判断文件test1是否可读,如果是,则输出 is readable !的提示信息;否则不进行任何动作。

[root@localhost 20190105]# vi test.sh
filename=test1
if [ -r $filename ]            //输出test1可读则输出信息
then
echo $filename' is readable !'
fi
[root@localhost 20190105]# sh test.sh
test1 is readable !

shell脚本会判断number变量是否等于100,如果是,则输出 the number is equal 100 !的提示;否则输出 the number is not equal 100 !。

[root@localhost 20190105]# vi number.sh
number=200
if [ $number -eq 100 ]                 //如果number等于100则输出“the number is equal 100 !”提示
then
       echo 'the number is equal 100 !'
else                            //否则输出“the number is not equal 100 !”提示
       echo 'the number is not equal 100 !'
fi
[root@localhost 20190105]# sh number.sh
the number is not equal 100 !

shell脚本首先判断number变量是否小于10,如果是则输出 the number < 10 !;否则,判断number变量是否大于等于10且小于20。

如果是则输出 10 =< the number < 20 !;否则,判断 number变量是否大于等于20且小于30。

如果是,则输出 20 =< the number < 30 !;否则,输出 30 <= the number !。

[root@localhost 20190105]# vi number1.sh
number=25
if [ $number -lt 10 ]              //如果number小于10
then
       echo 'the number < 10 !'
elif [ $number -ge 10 -a $number -lt 20 ] //如果number大于等于10且小于20
then
       echo '10 =< the number < 20 !'
elif [ $number -ge 20 -a $number -lt 30 ] //如果number大于等于20且小于30
then
       echo '20 =< the number < 30 !'
else                         //除上述3种情况以外的其他情况
       echo '30 <= the number !'
fi
[root@localhost 20190105]# sh number1.sh
20 =< the number < 30 !

现在你可以复制并修改测试脚本,加入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部分结束。 

到此这篇关于shell结构化命令if-then-else语句的文章就介绍到这了,更多相关shell if-then-else内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com