0

I'm new to BASH and I have to write a BASH file.

I have this if statement

if [[ ${disp} != ?(-)+([0-9]) ]] || [[ $disp -ne 1 ]] || [[ $disp -ne 0 ]]
    then
        echo -e "Parametro disponibilidade tem que ser '0' ou '1'!"
        echo -e "disponivel - 1, indisponivel - 0" 
        exit 1
fi

The second and the third conditions don't work. However if I delete the last condition

if [[ ${disp} != ?(-)+([0-9]) ]] || [[ $disp -ne 1 ]]
    then
        echo -e "Parametro disponibilidade tem que ser '0' ou '1'!"
        echo -e "disponivel - 1, indisponivel - 0" 
        exit 1
fi

The last condition works!! Can't someone explain me why this happens and how would you do it?

It should check if the user input is an integer and that integer must be 0 or 1, else bash exits

Thanks for your help

  • 4
    Many beginners confuse "or" and "and"; is that the problem here? Can you show some values of `$disp` which don't work like you expect? – tripleee Mar 04 '21 at 19:21
  • `[[ ${disp} != ?(-)+([0-9]) ]]` looks like you are trying to use extended globs; are you sure this feature is enabled in your script? – tripleee Mar 04 '21 at 19:22
  • 2
    Also, with `[[ ... ]]`, you can use the boolean operators inside the condition, i.e. `[[ $disp != ?(-)+([0-9]) || $disp -ne 1 || $disp -ne 0 ]]` – choroba Mar 04 '21 at 19:23
  • if $disp==0 or $disp==1 the bash exits – Nuno Monteiro Mar 04 '21 at 19:23
  • [[ ${disp} != ?(-)+([0-9]) ]] works fine, i'm just checking if the user input other than integers. user must input 0 or 1, else bash exits – Nuno Monteiro Mar 04 '21 at 19:25
  • 4
    Note that at least one of the conditions `[[ $disp -ne 1 ]]` and `[[ $disp -ne 0 ]]` will always be true, so the `then` block will always be executed. You probably need `[[ $disp -ne 1 && $disp -ne 0 ]]` to test for 0 or 1. I'm not sure about the first term, but (as alluded to by @tripleee), confusion over 'and' vs 'or' is quite common, especially with negated conditions in the separate terms. – Jonathan Leffler Mar 04 '21 at 19:30
  • Exactly, that was my problem. thank you so much. It's solved – Nuno Monteiro Mar 04 '21 at 19:38

0 Answers0