Given command that requires flag --flag. We want to insert this flag only when the value of the flag is provided as environment variable VALUE.

I tried the following:

echo "command ${X+--flag ${VALUE}}"
echo "command ${X+--flag ${VALUE}}"'


1 Answer 1

command ${VALUE:+--flag "$VALUE"}

This runs command with the option --flag and its option-argument "$VALUE" if the variable VALUE is defined and non-empty. If the variable is empty or undefined, it runs command without arguments.

In the zsh shell, which does not perform word-splitting on unquoted expansions, you will have to set the SH_WORD_SPLIT shell option (setopt SH_WORD_SPLIT), run the shell in sh compatibility mode (zsh --emulate sh), or use

command ${=VALUE:+--flag "$VALUE"}

... to ensure that --flag and "$VALUE" are passed as two separate arguments when VALUE is set to a non-empty value.

Remove the : in the parameter substitution if you want the --flag option added when VALUE is defined but empty.

  • 1
    Note that it doesn't work in zsh when not in sh emulation (shwordsplit option enabled) in that it passes one argument with an embedded space. command ${VALUE+--flag} ${VALUE+"$VALUE"} for code compatible to all. Mar 6 at 15:29
  • Thanks for this comment. This is what greatly confused me! What is the closest syntax that is portable to zsh?
    – A B
    Mar 6 at 15:32
  • 1
    @StéphaneChazelas I hope I addressed that now.
    – Kusalananda
    Mar 6 at 15:32
  • You don't want the : as the OP didn't specify that the empty string should be handled specially. Mar 6 at 15:33
  • @StéphaneChazelas I do, if I want to trigger the expansion only on non-empty values of $VALUE. I'll add a note.
    – Kusalananda
    Mar 6 at 15:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .