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)