0

I am using a optional variable BUILD_X flag to decide whether to build X based on user input.

BUILD_X=true
while getopts "B:" option; do
  case "$option" in
    B) BUILD_X=$OPTARG;;
  esac
done

if (( $BUILD_X == true )); then
    body
fi

I am observing that even if I give BUILD_X false from the terminal as an input to script, it still executes the body. Where am I going wrong ?

5
  • The shell's only primitive data type is the string. false is simply the string "false" and does not have a boolean value.
    – tripleee
    Commented Feb 13, 2023 at 7:28
  • @tripleee so how do I correct this code ?
    – Cool Camel
    Commented Feb 13, 2023 at 7:33
  • The usual solution would be to not have an argument for the option and just set the variable if the option is present. So getopts "B" and if that is true then set X_BUILD=""; then in your conditional you can simply say if [[ "$X_BUILD" ]]; then
    – tripleee
    Commented Feb 13, 2023 at 7:37
  • @tripleee using if [[ "$BUILD_X" == true ]] works but (( )) round brackets are not working ? I don't understand why because both can be used for comparisions
    – Cool Camel
    Commented Feb 13, 2023 at 7:44
  • (( ... )) is mathematical context, it works fine for numbers but this is a string.
    – tripleee
    Commented Feb 13, 2023 at 7:46

0

Browse other questions tagged or ask your own question.