How can I quote a string with single quotes?
Eg, I can do:
$ printf "%q\n" 'two words'
two\ words
$
Is there a way to get a single- (or double-) quoted string as output, ie:
$ MAGIC 'two words'
'two words'
$
I find the single-quoted version much easier to read.
I'd like an answer which works for {ba,z}sh. POSIX shell would be a bonus.
Best Answer
Assuming that:
posix
quote () { printf %s\\n "$1" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/'/" ; }
Use:
From Rich's sh posix tricks
Warning: the ESC (\033 or \x1b or decimal 27) characters above gets (technically) quoted, but is invisible. When sent to a terminal, like other control characters, could even do harm. Only when they are visually presented as $'\033', $'\C-[' or $'\E', they are clearly visible and unambiguous.
bash
printf '%s\n' "${value@Q}" $'This isn\'t a \n\E "correct" test'
zsh
printf '%s\n' ${(q)value} This\ isn\'t\ a\ $'\n'$'\033'\ \"correct\"\ test
zsh
printf '%s\n' ${(qq)value} 'This isn'\''t a "correct" test'
zsh
printf '%s\n' ${(qqq)value} "This isn't a \"correct\" test"
zsh
printf '%s\n' ${(qqqq)value} $'This isn\'t a \n\033 "correct" test'
zsh
printf '%s\n' ${(q-)value} 'This isn'\''t a "correct" test'
zsh
printf '%s\n' ${(q+)value} $'This isn\'t a \n\C-[ "correct" test'
Be careful with some zsh quoted strings: the ESC (\033 or \x1b or decimal 27) characters above are all (technically) quoted, but invisible. When sent to a terminal, like other control characters, could even do harm. Only when they are visually presented as $'\033', $'\C-[' or $'\E', they are clearly visible and unambiguous.
From Bash's manual:
From the
zshexpn
man page: