Pulkit
Pulkit

Reputation: 127

bash if else and variable assignment

How can I add an if else in between a variable assignment?

Something like:

var="statement "[ $var2 -eq 0 ] && "is true" || "is false"

I want to avoid:

if [ $var2 -eq 0 ]; then
    var="statement is true"
else
    var="statement is false"
fi

Can this be done?

Thanks

Upvotes: 1

Views: 1270

Answers (3)

SaintHax
SaintHax

Reputation: 1943

Not sure there's anyway that could be considered good coding, but here's two ways that are concise (please add a comment in your code as to what's going on, if you use these)

This way initializes your variable "var", and evaluates "var1" (also don't use these variable names ever, even in posts to SO) to see if it's a non-zero/null value. Then appends either true or false.

var="statement is "
(($var1)) && var+=true || var+=false

The other way is to change your logic, to have var set to "" (nothing) if false, and set to "true" if true. Then have an unset variable default to "false", and return the true that's assigned to it if set. Man bash, search for `:-' for more info.

var="statement is ${var1:-false}"

Upvotes: 1

Benoit
Benoit

Reputation: 79185

$(...) expressions nest inside pairs of double quotes

Therefore, you can do the following:

var="abc$( (($var2==0)) && printf '%s' ' is true' || printf '%s' ' is false')"

Upvotes: 0

heemayl
heemayl

Reputation: 42017

Do:

[ "$var2" -eq 0 ] && var="statement is true" || var="statement is false"

Technically, var="statement is false" wil run if either [ "$var2" -eq 0 ] or var="statement is true" fails but the chance of failure of var="statement is true" is practically nearly null.

Upvotes: 2

Related Questions