2

In PHP, I can assign a variable like this:

$a = ($b == $c) ? $x : $y; 

Which assigns to $a the value $x iff $b == $c, and $y otherwise. Is there a way to do this natively in bash?

I am aware that it is possible using a conventional if statement, or using a subshell with echo, but I was hoping there might be a simple way to do it. Writing a 6-line if statement or using a subshell seems like a lot for such a basic operation.

1 Answer 1

3
[[ $b = $c ]] && a="$x" || a="$y" 
Sign up to request clarification or add additional context in comments.

2 Comments

It also seems to work with single [, any reason [[ is better?
the main advantage, in my view, is that [ is more fragile regarding empty values when you don't quote variables. example: b=5; c=; [[ $b != $c ]] && echo ok; [ $b != $c ] && echo ok

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.