2

I know I can do:

echo ${var:-4}

to print 4 if var is null,

but how to assign -n in this case..?

echo ${var:--n} does not work.

although this does work..

echo ${var:---n}

but in that case it prints out --n and I need it to print -n.

branquito
  • 3,864
  • 5
  • 35
  • 60
  • 2
    `echo` is literally allowed to do **anything** when passed `-n` as an argument. See [the POSIX specification](http://pubs.opengroup.org/onlinepubs/009604599/utilities/echo.html): *"If the first operand is `-n`, or if any of the operands contain a backslash ( '\' ) character, the results are implementation-defined"*. When passed `-n`, or any content with literal backslashes, `echo` could turn a backflip or kill your cat and still be POSIX-compliant. Follow the advice in the APPLICATION USAGE section of the spec, and use `printf` instead. – Charles Duffy Oct 11 '16 at 23:08
  • Possible duplicate of [Assigning default values to shell variables with a single command in bash](http://stackoverflow.com/questions/2013547/assigning-default-values-to-shell-variables-with-a-single-command-in-bash) – Elmar Peise Oct 11 '16 at 23:09
  • @ElmarPeise, ...I'm not sure it is -- the immediate cause is certainly different, at least. – Charles Duffy Oct 11 '16 at 23:09

1 Answers1

8

The problem is not in the default, but in echo: -n has a special meaning for it (check help echo). Use printf instead:

printf '%s\n' "${var:--n}"
choroba
  • 231,213
  • 25
  • 204
  • 289
  • Yes, I knew about `-n` in echo.. but it didn't occur to me at the moment.. Interestingly this happened as a side effect.. if I happened to try with `${var:--a}`, it would work ;) – branquito Oct 11 '16 at 23:22