簡體   English   中英

bash腳本中的多個條件變量

[英]Multiple conditions variables in bash script

我需要這樣做:

if [ $X != "dogs" and "birds" and "dogs" ]
then
    echo "it's is a monkey"
fi

與bash腳本。 如何進行?

您需要將每個選項轉換為單獨的條件表達式,然后將它們與&& (AND)運算符連接在一起。

if [[ $X != dogs && $X != birds && $X != cats ]]; then
  echo "'$X' is not dogs or birds or cats.  It must be monkeys."
fi

您也可以使用單個[ ... ]進行此操作,但隨后必須為每個比較使用單獨的集合,並將and運算符移到它們之外:

if [ "$X" != dogs ] && [ "$X" != birds ] && [ "$X" != cats ]; then
   ...
fi

請注意,您不需要在諸如dogs類的單字字符串周圍加上雙引號,但在單括號版本中確實需要在諸如$X類的參數擴展(變量)周圍使用雙引號,因為參數值中的空格會導致沒有引號的語法錯誤。

另外,無需在外殼程序腳本中使用大寫的變量名,如X 最好保留來自環境的變量,例如$PATH$TERM等。

OR的shell運算符版本為|| ,其工作方式相同。

您甚至可以考慮不同...

if ! [[ $X == dogs || $X == birds || $X == cats ]]; then
    echo "'$X' is not dogs or birds or cats... It could be monkeys."
fi

作為思考:

不是狗,不是貓,也不是鳥

與思考並不完全相同

它不是..狗,貓或鳥之一。

這使得case的處理方式更加明顯。 我認為,在這種情況下,正確的做法是:

case $X in
    dogs )
        # There may be some part of code
        ;;
    birds )
        # There may be some other part
        ;;
    cats )
        # There is no need to be something at all...
       ;;          
    * )
       echo "'$X' is not dogs or birds or cats... It could be monkeys."
       ;;
esac

或者,如果真的不需要處理鳥,貓或狗的情況:

case $X in
    dogs|birds|cats ) ;;
    * )
       echo "'$X' is not dogs or birds or cats... It could be monkeys."
       ;;
esac

我能想到的唯一避免在Bash中放置$ X的方法是使用RegEx:

if [[ ! "$X" =~ (dogs|birds|cats) ]]; then
    echo "it's is a monkey"
fi

同樣,簡而言之:

[[ ! "$X" =~ (dogs|birds|cats) ]] && echo "it's is a monkey"

當您有很長的變量和/或很短的比較時,這很有用。

記住要轉義特殊字符。

X=$1;
if [ "$X" != "dogs" -a "$X" != "birds" -a "$X" != "dogs" ]
then
    echo "it's is a monkey"
fi

最接近您已有的

暫無
暫無

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

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