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"?
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"
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'
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")
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-
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With