-3

in my bash script I did the following syntax in order to verify if $Val is boolean

if [[ $Val != True ]] && [[ $Val != False ]];then
    echo "sorry but Val isn't a boolean"
    exit 1
else
    echo "good state $Val is a boolean"
fi

any other idea how to do it more elegant?

so if $Val is True or False , then its good state if not then we do exit 1

when I use "[[ $Val != @(True|False) ]]" ,

then in my python charm editor I get:

enter image description here

jessica
  • 2,426
  • 24
  • 66
  • Does this answer your question? [How can I declare and use Boolean variables in a shell script?](https://stackoverflow.com/questions/2953646/how-can-i-declare-and-use-boolean-variables-in-a-shell-script) – Antonio Petricca Jun 16 '21 at 14:17
  • Look at https://stackoverflow.com/questions/2953646/how-can-i-declare-and-use-boolean-variables-in-a-shell-script . – Antonio Petricca Jun 16 '21 at 14:17

2 Answers2

0

Use an extended glob:

if [[ $Val != @(True|False) ]]; then
  echo "sorry but Val isn't a boolean" >&2
  exit 1
fi

# continue with good value of Val

Older versions of bash may require you to explicitly enable extended globs with shopt -s extglob first, but newer versions temporarily enable the option inside [[ ... ]].

chepner
  • 497,756
  • 71
  • 530
  • 681
  • from some unclear reason I get error in my python charm GUI with red line under $val – jessica Jun 16 '21 at 14:49
  • Because PyCharm is probably trying to parse this as Python, not shell. – chepner Jun 16 '21 at 15:02
  • as you know python charm can use also for shell script or bash , all my bash script are edit correctly – jessica Jun 16 '21 at 15:18
  • I don't know; I don't use PyCharm, and nothing I've ever read about it hear makes me interested in trying it out. But whether the *editor* understands the syntax of the file you are editing is independent of whether you can execute it with the appropriate interpreter. – chepner Jun 16 '21 at 15:38
0

The standard shell case construct may be used for that. It can match a given string against one or more shell patterns:

case $Val in
  True | False) echo "good state $Val is a boolean";;
  *) echo "sorry but Val isn't a boolean"; exit 1;;
esac >&2

Alternative patterns for the same case are separated by |. Unquoted leading or trailing blanks in the pattern are ignored.

The list for a case may be empty. So if you just wanted to exit after failing to match "True" or "False", you can do that:

case $Val in
  True | False) ;;
  *) echo "sorry but Val isn't a boolean"; exit 1;;
esac >&2