1

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

3
  • Not directly, no. There are some string substitutions which behave differently depending on whether a variable is undefined (or defined but empty) or not, but nothing which treats the string "0" as particularly significant. Commented Apr 18, 2016 at 12:41
  • For a really opaque solution, you could exploit the fact that $0 will be set but other positional parameters will be empty in a function with no parameters. Commented Apr 18, 2016 at 12:43
  • 3
    Don't avoid the longer form. Anything you come up with that is shorter is going to be less clear in the long run and isn't worth it. Commented Apr 18, 2016 at 12:55

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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}"

Comments

0

$(...) 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')"

2 Comments

I feel I have written an abomination.
Prepopulate an array bool=(false true), then index it directly with the comparison. printf 'abc is %s\n' "${bool[var2==0]}". (And if var2 is {0,1}-valued, you don't even need the comparison, obviously.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.