shell入门(4)——选择结构

选择结构

在高级语言中,选择结构也是经常用到的,几乎是用的最多的一种结构

语言和语言之间是相通的,在shell中也有选择结构,而且与高级语言相似,具体如下

if else结构

语法结构

if condition
then 
    command
    ...
else
    command
    ...
fi

示例

a="test"
b="test"
if[ $a = $b ] 
then
    echo 'a=b'
fi

//结果输出 a=b

if elseif else结构

语法结构

if condition
then 
    command
    ...
elif condition
    command
    ...
else 
    command
fi

示例

a="1"
b="2"
if[ $a = $b ] 
then
    echo 'a=b'
elif [ $a < $b ]
then
    echo 'a<b'
else
    echo 'a>b'
fi

//结果输出 a=b

注意事项

if后面的表达式,即[]中的内容,前后都要预留一个空格,否则shell会报错,无法识别命令

错误示范

a="test"
b="test"
if[ $a = $b] 
then
    echo 'a=b'
fi

//结果输出 a=b

猜你喜欢

转载自blog.csdn.net/x1032019725/article/details/81104168