Assign result of conditional expression to environment variable
Olivia Zamora
I'd like to store the result of a conditional expression in an environment variable.
I tried:
C=$([ "$A" = "$B" ])but the value of $C after running that is an empty string.
I could of course do something like this:
if [ "$A" = "$B" ]
then C=1
else C=0
fibut I'm sure there's a better way of doing it.
32 Answers
I believe the simplest solution is this:
C=$(! [ "$A" = "$B" ]; echo $?)This just negates the exit code of the test command and assigns it to $C.
Use an expression like this:
variable=$([ "A" == "B" ] && echo "true" || echo "false") 6