Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

Assign result of conditional expression to environment variable

Writer 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
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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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