Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash boolean expression and its value assignment

Tags:

bash

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 ?

like image 652
sakhunzai Avatar asked Mar 28 '12 10:03

sakhunzai


People also ask

How do you assign a value to a Boolean?

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”.

How do you set a Boolean value in bash?

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.

Does bash have Boolean variables?

Bash does not support Boolean values, but any bash variable can contain 0 or “true” and 1 or “false“.

Is 1 true or false in bash?

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.


2 Answers

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.

like image 67
Mat Avatar answered Sep 28 '22 09:09

Mat


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.)

like image 28
Andrew Avatar answered Sep 28 '22 09:09

Andrew