shell if/then/elif/else/fi

shell中用if/then/elif/else/fi实现分支控制,本质上是由若干条shell命令组成。

例如

if [ -f  ~/.bashrc ]; then
        . ~/.bashrc
fi

如果两条命令需要在同一行写,那么用;隔开,一行只写一个命令则不需要用;隔开。

命令与各参数之间需要用空格隔开。

if 后面的子命令,如果该命令的exit status为0则表示为真,则执行then后面的子句。

                            如果为假那么则执行elif,else或者fi后面的子命令。

这个子命令通常为测试命令。shell脚本中没有{},所以用fi来表示if语句块的结束。

#! /bin/sh

if [ -f /bin/basn ]
then echo "/bin/bash is a file"
else echo "/bin/bash is NOT a file"
fi
if :;then echo "always true";fi

:是一个空命令,这个命令不做任何事情,结果永为真。此外,也可以执行/bin/true或/bin/false得到真或假的exit status

#!/bin/sh

echo "Is It morning? Please answer yes or no"
read YES_OR_NO
if [ "$YES_OR_NO"="yes" ];then
echo "Good morning!"
elif [ "YES_OR_NO"="no" ];then
echo "Good afternoon!"
else

这个例子中,read命令的作用是等待用户输入一个字符串,将该字符串储存在shell变量之中。

shell提供了&&与||语法,与C语类似,具有Short-circuit特性

&&的作用相当于if then

||              相当于if not.....then

 例如

[root@localhost ~]# test "$(whoami)"!="root" && (echo you are using a non-privileged account; exit 1)
you are using a non-privileged account


[root@localhost ~]# test "$(whoami)"!="root" || (echo you are using a non-privileged account; exit 1)
[root@localhost ~]# 


#一个执行了后面的语句另一个并没有

猜你喜欢

转载自blog.csdn.net/weixin_38280090/article/details/81835142