0

I'm not finding this answer, and it's got to be obvious, but I still need the help.

In an attempt to create a command line option, I was using the various flags and echoing them to verify they were right.

This example, however, continued to fail:

declare foo="-n 40 "
echo $foo

When run it just shows '40'.

If I add another dash in front of -n, it prints --n A backslash/escape? It prints that. In short, I can't figure out what the heck is going on to get that simple text to display properly. I've even tried using the -- (stop processing) to no avail.

So please, if possible, point me to where in the documentation and explain why it's interpreting that -n so that I can learn to not do it, and work around it, in the future.

Thank you.

Bart
  • 2,221
J.Hirsch
  • 103
  • 2
  • Ultimately the problem is due to 'echo' interpreting the -n. However when I ran into the problem I was not recognizing that as the error, and instead thinking 'declare' or something in the bash interpreter was chewing up the text. It's your call as (knowing now) that echo was the problematic part, the 'how can I print "-n" is spot on and the correct issue I was trying to address. The searches I did for an answer did not lead me to that issue though. – J.Hirsch Aug 30 '19 at 13:26

1 Answers1

3

The echo bash builtin interprets -n as a parameter of itself (as documented in help echo or man bash).

-n do not append a newline

Some other echo implementations do the same.

Use printf instead.

printf '%s\n' "$foo"
Kusalananda
  • 333,661
choroba
  • 47,233
  • Is there no way to easily override it? Or is it safe to build all of my commands with that new syntax ? edit: I should have thought to check the echo man page as well. Thank you for pointing that out. – J.Hirsch Aug 30 '19 at 13:02