0
#!/bin/bash

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

echo "still runs"

Here is the run sh -x ./test.sh dsm_label jqm_labe but it does not exit and seems to ignore the check for 2nd parameter. it is supposed to check for both the parameters and then exit

+ [[ dsm_label =~ ^(dsm_print|dsm_label)$ ]]
+ echo 'still runs'
still runs
5
  • Does it work as expected if you run it with bash instead of sh? What's your operating system? What is sh on your system?
    – terdon
    Oct 21, 2022 at 19:44
  • yes, bash also gives the same error. $1 should be dsm_print or dsm_label. $2 should be jqm_print or jqm_label and it should check both
    – munish
    Oct 21, 2022 at 19:46
  • What error? What are you expecting this to do? Your test will only fail if both $1 and $2 are wrong. Is that what you really want?
    – terdon
    Oct 21, 2022 at 19:48
  • Your test will only fail if both $1 and $2 are wrong. Is that what you really want? yes
    – munish
    Oct 21, 2022 at 19:48
  • Wait, what? Then it works as expected. Are you sure you don't want it to fail if either is wrong and only want it to fail when both are wrong?
    – terdon
    Oct 21, 2022 at 19:51

1 Answer 1

2

If you want to check both parameters, you want || not &&. As it stands, your script will only fail if you give both wrong:

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

That's because if ! [[ condition1 ]] && ! [[ condition2 ]] will only be true if both conditions are false. What you want is || so it will fail if either of them is false:

#!/bin/bash

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

echo "still runs"

This works as expected:

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .