条件组合

我们可以使用和(&&)或者(||)命令组合多个测试条件。

#!/bin/bash
dir=/home/onitroad
name="onitroad"
if [ -d $dir ] && [ -n $name ]; then
	echo "The name exists and the folder $dir exists."
else
	echo "One test failed"
fi

如果两个测试成功,则此示例将返回true;否则,它将返回false。

条件或者:

#!/bin/bash
dir=/home/onitroad
name="onitroad"
if [ -d $dir ] || [ -n $name ]; then
	echo "Success!"
else
	echo "Both tests failed"
fi
bash shell if-then-else 语句

在shell脚本中, if-then-else语句采用以下结构:

if command; then

do something

else

do another thing

fi

如果第一个命令运行并返回零,这意味着成功,它将不会执行else语句后面的命令;
否则,如果if语句返回非零;这意味着条件语句失败,在这种情况下,shell将执行else语句之后的命令。

shell if条件语句示例:

#!/bin/bash
user=anotherUser
if grep $user /etc/passwd; then
	echo "The user $user Exists"
else
	echo "The user $user doesn’t exist"
fi

如果我们需要多个else语句呢?
这可以通过嵌套if语句来实现:

if condition1; then

commands

elif condition2; then

commands

fi

示例:

#!/bin/bash
user=anotherUser
if grep $user /etc/passwd; then
	echo "The user $user Exists"
elif ls /home; then
	echo "The user doesn’t exist"
fi
日期:2020-07-15 11:16:52 来源:oir作者:oir