echo “-n” will not print -n?

2019-02-16 10:46发布

问题:

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"?

回答1:

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



回答2:

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-


回答3:

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"


回答4:

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'


回答5:

echo "-n" will not print -n because -n is interpreted as an option for echo (see help echo). But you can use:

echo -e "\055n"


回答6:

Cheating method:

echo -e  "\r-n"


标签: bash echo