Is there a way to to evaluate a boolean expression and assign its value to a variable?
In most of the scripting languages there is way to evaluates e.g
//PHS $found= $count > 0 ; //evaluates to a boolean values
I want similar way to evaluate in bash:
BOOL=[ "$PROCEED" -ne "y" ] ;
This is not working and tried other way but could not get a boolean value. IS there a way to do this WITHOUT using IF ?
To declare a Boolean variable, we use the keyword bool. To initialize or assign a true or false value to a Boolean variable, we use the keywords true and false. Boolean values are not actually stored in Boolean variables as the words “true” or “false”.
There are no Booleans in Bash Wherever you see true or false in Bash, it's either a string or a command/builtin which is only used for its exit code. where the command is true . The condition is true whenever the command returns exit code 0.
Bash does not support Boolean values, but any bash variable can contain 0 or “true” and 1 or “false“.
There are no Booleans in Bash. However, we can define the shell variable having value as 0 (“ False “) or 1 (“ True “) as per our needs. However, Bash also supports Boolean expression conditions.
You could do:
[ "$PROCEED" = "y" ] ; BOOL=$?
If you're working with set -e
, you can use instead:
[ "$PROCEED" = "y" ] && BOOL=0 || BOOL=1
BOOL
set to zero when there is a match, to act like typical Unix return codes. Looks a bit weird.
This will not throw errors, and you're sure $BOOL
will be either 0 or 1 afterwards, whatever it contained before.
I would suggest:
[ "$PROCEED" = "y" ] || BOOL=1
This has the advantage over checking $?
that it works even when set -e
is on. (See writing robust shell scripts.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With