Jack Wilsdon
Jack Wilsdon

Reputation: 7025

Bash multiple parameter substitution

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?

Upvotes: 0

Views: 358

Answers (4)

rici
rici

Reputation: 241771

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

Upvotes: 1

anubhava
anubhava

Reputation: 785266

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

Upvotes: 1

ghoti
ghoti

Reputation: 46856

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.

Upvotes: 1

Jean-François Fabre
Jean-François Fabre

Reputation: 140196

One line, requirement met:

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

Upvotes: 0

Related Questions