2

I understand the empty string in Bash is falsy, and we should be able to use something like

a=""
b=($a || 0)

which means if $a is falsy, then just make it 0. But it gave

bash: syntax error near unexpected token `||'

and I understand we can use [-z $a] and use the Bash ternary form:

a=""
[[ -z $a ]] && b=0 || b=$a

But is there a way to use something similar to the first form above that works in both Bash and Zsh?

nonopolarity
  • 146,324
  • 131
  • 460
  • 740
  • (the duplicate doesn't ask about zsh explicitly, but the answers suggest POSIXy syntax that, while not a standard-compliant shell, zsh does support). – Charles Duffy Dec 08 '20 at 12:43
  • If you intend to use the variable in an arithmetic context, and empty or unset variable *already* defaults to zero, as long as you don't explicitly expand it. `unset b; `echo $((3 + b))` outputs 3. – chepner Dec 08 '20 at 14:01

1 Answers1

3

You can use parameter expansion: ${PARAMETER:-WORD} will, if the variable PARAMETER is unset or an empty string, evaluate to WORD, otherwise the value of PARAMETER.

So:

b=${a:-0}
Shawn
  • 47,241
  • 3
  • 26
  • 60