找出多个条件中哪个为真
Find out which of the multiple conditions is true
我有一个脚本,可以检查 if 语句中的多个条件,运行 如果条件为真,则需要一个所需的命令。
if [ ! -f /tmp/a ] && [ ! -f /tmp/b ]; then
touch /tmp/c else
echo "file exists" fi
我现在需要知道多个条件中哪一个为真。
例如:/tmp/a 或 /tmp/b 曾经存在过。有没有办法在我的 else 条件下得到它?
由于您的 if
使用的是复合条件,因此 else
无法确定复合条件的哪一部分失败了。您可以这样重写代码:
a_exists=0
b_exists=0
[[ -f /tmp/a ]] && a_exists=1 # flag set to 1 if /tmp/a exists
[[ -f /tmp/b ]] && b_exists=1 # flag set to 1 if /tmp/b exists
if [[ $a_exists == 0 && $b_exists == 0 ]]; then
touch /tmp/c
else
[[ $a_exists == 1 ]] && echo "a exists"
[[ $b_exists == 1 ]] && echo "b exists"
fi
上面的代码可以用Bash算术运算符(( ... ))
:
写得更简洁
a_exists=0
b_exists=0
[[ -f /tmp/a ]] && a_exists=1 # flag set to 1 if /tmp/a exists
[[ -f /tmp/b ]] && b_exists=1 # flag set to 1 if /tmp/b exists
if !((a_exists + b_exists)); then
touch /tmp/c
else
((a_exists)) && echo "a exists"
((b_exists)) && echo "b exists"
fi
这听起来像是有一天要检查两个以上的文件。使用循环:
i_am_happy=yeah
for f in a b
do
if [[ ! -f /tmp/$f ]]
then
echo "Criminy! No $f in tmp!" # or what else you would like to do.
i_am_happy=nope
fi
done
[[ i_am_happy == nope ]] && touch /tmp/c
我有一个脚本,可以检查 if 语句中的多个条件,运行 如果条件为真,则需要一个所需的命令。
if [ ! -f /tmp/a ] && [ ! -f /tmp/b ]; then
touch /tmp/c else
echo "file exists" fi
我现在需要知道多个条件中哪一个为真。 例如:/tmp/a 或 /tmp/b 曾经存在过。有没有办法在我的 else 条件下得到它?
由于您的 if
使用的是复合条件,因此 else
无法确定复合条件的哪一部分失败了。您可以这样重写代码:
a_exists=0
b_exists=0
[[ -f /tmp/a ]] && a_exists=1 # flag set to 1 if /tmp/a exists
[[ -f /tmp/b ]] && b_exists=1 # flag set to 1 if /tmp/b exists
if [[ $a_exists == 0 && $b_exists == 0 ]]; then
touch /tmp/c
else
[[ $a_exists == 1 ]] && echo "a exists"
[[ $b_exists == 1 ]] && echo "b exists"
fi
上面的代码可以用Bash算术运算符(( ... ))
:
a_exists=0
b_exists=0
[[ -f /tmp/a ]] && a_exists=1 # flag set to 1 if /tmp/a exists
[[ -f /tmp/b ]] && b_exists=1 # flag set to 1 if /tmp/b exists
if !((a_exists + b_exists)); then
touch /tmp/c
else
((a_exists)) && echo "a exists"
((b_exists)) && echo "b exists"
fi
这听起来像是有一天要检查两个以上的文件。使用循环:
i_am_happy=yeah
for f in a b
do
if [[ ! -f /tmp/$f ]]
then
echo "Criminy! No $f in tmp!" # or what else you would like to do.
i_am_happy=nope
fi
done
[[ i_am_happy == nope ]] && touch /tmp/c