0

I saw this mentioned in some documentation. But it doesn't seem to do anything...

~ $ echo $DYNO
run.9917
~ $ echo ${DYNO}
run.9917
~ $ echo ${DYNO:-1}
run.9917

What does the :-1 do?

John Bachir
  • 22,495
  • 29
  • 154
  • 227
  • unfortunately it's closed before i post my answer. here is a good reference for it: http://tldp.org/LDP/abs/html/refcards.html#AEN22728 – Jason Hu Mar 21 '15 at 20:39

3 Answers3

2

${DYNO:-1} means if DYNO exists and isn’t null, return its value; otherwise return 1. It's the :- between the variable's name and the default value inside the {} that make this happen.

Paul Evans
  • 27,315
  • 3
  • 37
  • 54
1

This is covered in the Shell Parameter Section of the Bash Reference Manual.

"${var:-1}" means expand the parameter named var if it's defined, and if not, expand 1 instead.

Other, similar expansions:

  • "${var: -1}" means expand the substring of var from the last character.
  • "${var:=1}" means assign 1 to var if it's not defined and then, either way, expand the parameter.

Examples:

$ x=hi y=
$ echo "${x:-1}" "${x: -1}" "${y:-2}"
hi i 2
kojiro
  • 74,557
  • 19
  • 143
  • 201
0

${var:-word} If var is null or unset, word is substituted for var. The value of var does not change.

$> echo "${bar:-1}"
$> 1
$> bar=3
$> echo "${bar:-1}"
$> 3
$> echo "${bar-1}"
$> 3
Roman Kiselenko
  • 43,210
  • 9
  • 91
  • 103
  • Thanks. Wanna add some examples? – John Bachir Mar 21 '15 at 20:22
  • http://stackoverflow.com/questions/10390406/usage-of-in-bash – robertjlooby Mar 21 '15 at 20:22
  • @JohnBachir. In short, `${var:-word}` allows `word` to serve as the **default value** for `var` in case `var` is **(1)** not already set, or **(2)** empty/null. There are other variations that change the circumstances under which `word` is used as the value for `var`. – David C. Rankin Mar 21 '15 at 20:32