Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

echo "-n" will not print -n?

Tags:

bash

echo

Very similar to this question.

I'm iterating through a few things with an automated script in BASH. Occasionally the script will come across "-n" and echo will attempt to interpret this.

Attempted this:

 $ POSIXLY_CORRECT=1 /bin/echo -n

and

 $ POSIXLY_CORRECT=1 /bin/echo "-n"

 

But it interpreted the argument each time.

Then this, which works but it's possible to hit escaped characters in the strings, which is why I don't want to apply a null character to all input and use -e.

$ echo -e "\x00-n"
-n

printf is possible, but is to be avoided unless there are no other options (Not all machines have printf as a utility).

$ printf "%s" "-n"
-n

So is there a way to get echo to print "-n"?

like image 286
Cellivar Avatar asked Nov 06 '12 20:11

Cellivar


4 Answers

echo "-n" tells the shell to put '-n' as echo's first argument, character for character. Semantically, echo "-n" is the same as echo -n. Try this instead (it's a POSIX standard and should work on any shell):

printf '%s\n' "-n"
like image 156
djhaskin987 Avatar answered Nov 20 '22 04:11

djhaskin987


If you invoke Bash with the name sh, it will mimic sh, where the -n option was not available to echo. I'm not sure if that fits your needs though.

$ /bin/sh -c 'echo -n'
like image 20
sidyll Avatar answered Oct 23 '22 17:10

sidyll


printf should be a built-in in all your shells, unless some of your machines have very old shell versions. It's been a built-in in bash for a long time. It's probably more portable than echo -e.

Otherwise, there's really no way to get echo options it cares about.

Edit: from an answer to another similar question; avoid quoting issues with printf by using this handy no-digital-rights-retained wrapper:

ech-o() { printf "%s\n" "$*"; }

(That's ech-o, as in "without options")

like image 10
rici Avatar answered Nov 20 '22 04:11

rici


What about prefixing the string with a character ("x" for instance) that gets removed on-the-fly with a cut:

echo "x-n" | cut -c 2-
like image 4
vladz Avatar answered Nov 20 '22 03:11

vladz