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.

3
  • 2
    echo is literally allowed to do anything when passed -n as an argument. See the POSIX specification: "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. Commented Oct 11, 2016 at 23:08
  • Possible duplicate of Assigning default values to shell variables with a single command in bash Commented Oct 11, 2016 at 23:09
  • @ElmarPeise, ...I'm not sure it is -- the immediate cause is certainly different, at least. Commented Oct 11, 2016 at 23:09

1 Answer 1

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}"
Sign up to request clarification or add additional context in comments.

1 Comment

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 ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.