0

I'm looking to set the value of a variable to one thing if it was already set or another if it was not. Here's an example of what I mean

export RESULT=${VALID:+Yes:-No}

Where the value of ${VALID:+Yes:-No} would be Yes if the variable was set or No if it was not.

One way I can do it now:

if [ -n "${VALID}" ]; then
  export RESULT=Yes
else
  export RESULT=No
fi

I could do it like this, but it would be nice to have a "one-liner".

Is it possible to do this in one line?

1
  • 1
    It might be of some interest to note that zsh will give the desired result with an expression like ${${VALID:+Yes}:-No}. Commented Aug 20, 2016 at 0:19

4 Answers 4

1

There's no way to do multiple parameter expansions within one variable assignement.

Without using an if statement, you can just use a couple of parameter expansions.

$ VALID="aaa"
$ RESULT="${VALID:+Yes}"; RESULT="${RESULT:-No}"; echo $RESULT
Yes
$ VALID=""
$ RESULT="${VALID:+Yes}"; RESULT="${RESULT:-No}"; echo $RESULT
No

It's not a single statement, but it's short enough that it fits on one line without the complexity of a subshell and if.

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

Comments

1

You can use an array with 2 elements (no yes) and based on variable's length decide which value to be returned:

# variable set case
>>> VALID=foo
>>> arr=(no yes) && echo "${arr[$((${#VALID} > 0))]}"    
yes

# variable not set
>>> unset VALID
>>> arr=(no yes) && echo "${arr[$((${#VALID} > 0))]}"    
no

Comments

1

The -v VAR printf option is a bash extension. Without it, you could use command substitution. (Variable names deliberately down-cased.)

printf -v result %.3s ${valid:+YES}NO

Comments

0

One line, requirement met:

export RESULT=$([ -n "$VALID" ] && echo Yes || echo No)

3 Comments

thanks Jack who edited, proposing an even shorter one-liner than my original answer.
Forking a new shell is an expensive way to avoid a single line of code.
Also, if you're going to allow an ...&&...||... construct, you may as well just write [ -n "$VALID" ] && export RESULT=Yes || export RESULT=No.

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.