sorin
sorin

Reputation: 170508

How to evaluate boolean like variable in bash in flexible way?

What is the portable way to evaluate a variable in bash as true regardless the way is defined.

Assuming we would use DEBUG name for the variable, this would be the evaluation logic:

A slight deviation from the spec above would be acceptable but the idea is the same, to give the user some flexibility regarding how he defines it, and avoid a execution failure due "unexpected input".

Extra kudos if someone find a clean way to implement it.

Upvotes: 0

Views: 93

Answers (2)

chepner
chepner

Reputation: 531345

While I don't recommend getting too flexible with the values you allow, I would use a case statement to match the allowed values explicitly, and raise an error for any other values.

DEBUG=${DEBUG:-0}  # As suggested by hek2mgl

shopt -s nocasematch  # Ignore the case of the value
case $DEBUG in
    0|false|no)
      echo "DEBUG is false"
      ;;
    1|true|yes)
      echo "DEBUG is true"
      ;;
    *)
      echo "Invalid setting for DEBUG: $DEBUG"
      exit 1
      ;;
esac

Upvotes: 1

hek2mgl
hek2mgl

Reputation: 158050

Set a reasonable default value for the variable:

DEBUG="${DEBUG:-0}"

Then, in your code, check:

if [ "${DEBUG}" -ne 0 ] ; then
    echo "DEBUG: foo ..."
fi

Further read: https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html

Upvotes: 2

Related Questions