11

Why doesn't $echo '-n' write -n on terminal although -n is written within single quotes?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Happy Mittal
  • 3,667
  • 12
  • 44
  • 60

6 Answers6

13

Because the quotes are processed by the shell and the echo command receives plain -n. If you want to echo -n, you can e.g. printf '%s\n' -n

laalto
  • 150,114
  • 66
  • 286
  • 303
4

I found that the following just works in bash:

echo -n PRINT_THIS

So, you should put -n the first place.

2

You should try to use the more portable printf as far as possible.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
  • Can you provide an example in your answer? (But ***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today.) – Peter Mortensen Nov 05 '21 at 16:49
2

You could try

echo -e '\055n'
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
0

The quotes don't help because ... ugh, it's hard to explain. The shell strips the quotes off before the "echo" command itself is evaluated, so by that time they don't matter.

Try this:

echo - -n

That's not documented as working (I'm running Ubuntu Linux), but echo is almost certainly a built-in to whatever shell you're using, so the man page is questionable anyway. It does work for me. (I'm running zsh because I'm really suave and sophisticated).

edit: well it seems that the bash builtin edit doesn't behave that way. I don't know what to suggest; this:

echo '' -n

will give you "-n" preceded by a space, which (depending on what you're doing) might be OK.

Pointy
  • 405,095
  • 59
  • 585
  • 614
0

Not quite there:

echo -e 'a-n\b\b\b '
 -n

Surprisingly, this works:

echo -e '-n\b'
-n

And here is a solution I can explain:

echo "foobar" | sed 's/.*/-n/'
-n
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user unknown
  • 35,537
  • 11
  • 75
  • 121