Shell-Script

為什麼這個 if 語句不能按預期工作?

  • October 21, 2022
#!/bin/bash

if ! [[ "$1" =~ ^(dsm_print|dsm_label)$ ]] && ! [[ "$2" =~ ^(jqm_print|jqm_label)$ ]]
then
echo "wrong parameters"
exit 1
fi

echo "still runs"

這是執行sh -x ./test.sh dsm_label jqm_labe,但它沒有退出,並且似乎忽略了對第二個參數的檢查。它應該檢查兩個參數然後退出

+ [[ dsm_label =~ ^(dsm_print|dsm_label)$ ]]
+ echo 'still runs'
still runs

如果要檢查這兩個參數,則||不需要&&. 就目前而言,如果您同時給出錯誤,您的腳本只會失敗:

$  foo.sh dsm_print wrong
still runs
$  foo.sh wrong jqm_label
still runs
$  foo.sh wrong wrong
wrong parameters

那是因為if ! [[ condition1 ]] && ! [[ condition2 ]]只有當兩個條件都為假時才會為真。您想要的是||,如果其中任何一個為假,它將失敗:

#!/bin/bash

if ! [[ "$1" =~ ^(dsm_print|dsm_label)$ ]] || ! [[ "$2" =~ ^(jqm_print|jqm_label)$ ]]
then
echo "wrong parameters"
exit 1
fi

echo "still runs"

這按預期工作:

$  foo.sh dsm_print wrong
wrong parameters
$  foo.sh wrong jqm_label
wrong parameters
$  foo.sh wrong wrong
wrong parameters

引用自:https://unix.stackexchange.com/questions/721950