0

Today I was testing a script and for some reason I needed to print -n to the console.

I tried echo -n, which of course just echos without a new line. I tried echo "-n", which does the same.

Then I tried assigning to a variable: str="-n". Of course echo $str and echo "$str" do nothing.

How would you echo exactly -n?

Barmar
  • 741,623
  • 53
  • 500
  • 612
jay
  • 493
  • 1
  • 3
  • 11

2 Answers2

5

Use printf rather than echo

printf '%s\n' '-n'
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

You could escape (\) both of those characters, telling your shell to read them both as literal characters.

Running echo \-\n gives me -n as output.

buddemat
  • 4,552
  • 14
  • 29
  • 49
  • 2
    Escaping it for the shell doesn't prevent `echo` from treating the `-` as an option indicator. And different versions of `echo` behave differently, so what works for your version may not for others -- see [this answer on U&L about `printf` vs `echo`](https://unix.stackexchange.com/questions/65803/why-is-printf-better-than-echo/65819#65819). (BTW, use [backticks to invoke code format](https://meta.stackoverflow.com/questions/251361/how-do-i-format-my-code-blocks).) – Gordon Davisson May 25 '22 at 07:46