Assign Result of Conditional Expression to Environment Variable

Assign Result of Conditional Expression to Environment Variable

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
fi

but I'm sure there's a better way of doing it.

3

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

2

Use an expression like this:

variable=$([ "A" == "B" ] && echo "true" || echo "false") 
6

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.