2

Sometimes I see in JavaScript:

a||=1

Which means - as far as I know - that if "a" is not defined, or null then it was initialized with value 1, otherwise nothing happens. I do the same in Ruby scripts, for example when a command line argument wasn't passed:

gamma=ARGV[0]||"1.0"

Then variable gamma gets its value from ARGV[0] assuming it is not nil, a value was passed, otherwise it will be "1.0".

It is a great shorthand for:

if ARGV[0]==nil then
  gamma="1.0"
else 
  gamma=ARGV[0]
end

and even:

gamma=ARGV[0]==nil ? "1.0" : ARGV[0]

I would like to use a similar cinstruction in a ruby script, but it doesn't work as expected, because a nil or null value doesn't exist, so expression:

$0||"1.0"

always gives the value of $0, even if it is an empty string "". Is it possible to use something similar shorthand syntax in bash scripts too?

Konstantin
  • 2,983
  • 3
  • 33
  • 55

1 Answers1

2

In bash you can use the Assign Default Values parameter expansion operator.

: ${a:=1.0}

${parameter:=word}
If parameter is unset or null, the expansion of word is assigned to parameter.

The : command is a no-op, it's used just so we can perform the parameter expansion in its argument list.

Barmar
  • 741,623
  • 53
  • 500
  • 612