if文が期待どおりに機能しないのはなぜですか?

if文が期待どおりに機能しないのはなぜですか?
#!/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終了せず、2番目の引数の確認を無視するようです。両方のパラメーターを確認してから終了する必要があります。

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

ベストアンサー1

両方のパラメータを確認したい場合は||必要ありません&&。現時点では、指定したエラーがすべて偽の場合にのみスクリプトが失敗します。

$  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

おすすめ記事