找出多个条件中的哪一个是真的

时间:2017-01-23 17:24:41

标签: bash shell if-statement multiple-conditions

我有一个脚本,它将在if语句中检查多个条件,并在其为true时运行所需的命令。

  if [ ! -f /tmp/a ] && [ ! -f /tmp/b  ]; then
        touch /tmp/c  else 
        echo "file exists"  fi

我现在需要知道多重条件中的哪一个是真的。 例如:/ tmp / a或/ tmp / b曾经存在过。有没有办法在我的其他情况下得到它?

2 个答案:

答案 0 :(得分:0)

由于您的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

答案 1 :(得分:0)

这闻起来有一天会检查两个以上的文件。使用循环:

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
相关问题