Sign up ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Is there an "inline-equivalent" to expressions like the following?:

if [[ $VERBOSE == 1 ]]; then
  V=$FOO
else
  V=
fi

I'm thinking of something like this in perl, for example:

$V = $VERBOSE ? $FOO : undef;

(BTW, my interest is not so much in the business of reducing five lines to one, since one could always re-write the shell snippet as

if [[ $VERBOSE == 1 ]]; then V=$FOO; else V=; fi

but rather in a single conditional expression that is equivalent to a multi-statement if-construct.)

In case there's a difference, I'm interested primarily in the answer for zsh, but also in the one for bash.

share|improve this question

4 Answers 4

up vote 3 down vote accepted

Zsh being zsh, there is a cryptic way:

V=${${VERBOSE#0}:+$FOO}

This sets V to the value of FOO if VERBOSE is a nonzero number, and to the empty string if VERBOSE is empty or 0.

V=${${${VERBOSE/#/a}:#a1}:+foo}

This sets V to the value of FOO if VERBOSE is the exact string 1, and to the empty string otherwise.

Now forget this and use the clear syntax with if or case.

If FOO is numeric, you can use the ?: operator in an arithmetic expression. The else case has to be numeric as well.

((V = VERBOSE ? FOO : 0))
share|improve this answer

Well, the closest I can think of would be

[[ $VERBOSE == 1 ]] && V="YES" || V="NO"

For example:

$ VERBOSE=0
$ [[ $VERBOSE == 1 ]] && V="YES" || V="NO"; echo $V
NO
$ VERBOSE=1
$ [[ $VERBOSE == 1 ]] && V="YES" || V="NO"; echo $V
YES

The above works for bash and zsh (and most other shells).

share|improve this answer
    
(most other shells being ksh. That's ksh syntax here). –  Stéphane Chazelas Feb 15 '14 at 20:57

You can use case/switches in Bash for this too. Just remember that they can't evaluate logic:

case "$VERBOSE" in
  1) V="YES" ;;
  *) V="NO"  ;;
esac
share|improve this answer

Competing for the most cryptic:

$ echo ${${(z):-NO YES}[2-!VERBOSE]}
NO
$ VERBOSE=123
$ echo ${${(z):-NO YES}[2-!VERBOSE]}
YES

Or:

$ echo ${${(z):-NO YES}:!!VERBOSE:1}
YES
share|improve this answer
    
I'll be chewing on these for some time... Thanks! –  kjo Feb 15 '14 at 22:08

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.