shell脚本if语句
if语句是shell脚本中的分支结构之一,它的基本语法如下:
if [ condition ]
then
statement(s)
fi
其中,condition是要测试的条件,then是条件为真时要执行的语句,fi则表示if语句的结束。
以下是一个简单的例子,演示如何使用if语句来判断一个数是否为正数:
#!/bin/bash
echo "Enter a number: "
read num
if [ $num -gt 0 ]
then
echo "The number is positive."
fi
在上面的例子中,输入一个数字后,脚本会判断这个数字是否大于0,如果是,则输出“The number is positive.”。
除了单条件的if语句,也可以使用双条件的if-else语句和多条件的if-elif-else语句。以下是一个使用if-else语句的例子,演示如何判断一个数的正负性:
#!/bin/bash
echo "Enter a number: "
read num
if [ $num -gt 0 ]
then
echo "The number is positive."
else
echo "The number is not positive."
fi
在上面的例子中,如果输入的数字大于0,则输出“The number is positive.”,否则输出“The number is not positive.”。
以下是一个使用if-elif-else语句的例子,演示如何判断一个数字的大小:
#!/bin/bash
echo "Enter a number: "
read num
if [ $num -gt 0 ]
then
echo "The number is positive."
elif [ $num -eq 0 ]
then
echo "The number is zero."
else
echo "The number is negative."
fi
在上面的例子中,如果输入的数字大于0,则输出“The number is positive.”,如果输入的数字等于0,则输出“The number is zero.”,否则输出“The number is negative.”。
原文地址: https://www.cveoy.top/t/topic/B8b 著作权归作者所有。请勿转载和采集!