#!/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
答案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