Reputation: 38694
How to print "-n", "-e" or "-neeenen" from bash (without a newline at the end, without invoking of external programs)?
Q="-n"
echo -n "$Q"
# fail
echo -- "$Q"
# fail
cat <<< "$Q"
# fail, also starts external program
printf -- '%s' "$Q"
# success, but starts external program
Upvotes: 3
Views: 530
Reputation: 359985
Of course, the correct and more portable way is to use printf
, however this works:
$ Q='-n'
$ echo -ne '\0'"$Q"
but it fails if you have backslash sequences that you want to print literally:
$ Q='-n\nX'
$ echo -ne '\0'"$Q"
-n
X
when what was wanted was "-n\nX". In this situation, this works:
$ echo -n $'\0'"$Q"
-n\nX$ # (no newline, so prompt follows on the same line)
but it doesn't for Q='-n'
!
What if we want to print the literal string with printf
?
$ Q='-n\nX'
$ printf "$Q"
-bash: printf: -n: invalid option
$ printf -- "$Q"
-n
X
$ printf "%s" "$Q"
-n\nX$ # (no newline, so prompt follows on the same line)
Upvotes: 0
Reputation: 60957
In bash, printf
is a builtin, so no external program is invoked.
$ help printf printf: printf [-v var] format [arguments]
printf formats and prints ARGUMENTS under control of the FORMAT. FORMAT is a character string which contains three types of objects: plain characters, which are simply copied to standard output, character escape sequences which are converted and copied to the standard output, and format specifications, each of which causes printing of the next successive argument. In addition to the standard printf(1) formats, %b means to expand backslash escape sequences in the corresponding argument, and %q means to quote the argument in a way that can be reused as shell input. If the -v option is supplied, the output is placed into the value of the shell variable VAR rather than being sent to the standard output.
Upvotes: 3