簡體   English   中英

找出多個條件中的哪一個為真

[英]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 。 有沒有辦法在我的其他條件下獲得它?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM