Python's standard library has a shlex.quote
function that takes a string and returns one that is guaranteed to be interpreted as that same string by Unix shells. This is achieved by putting the string in single quotes and escaping any occurrences of the single quote character that appear in it.
This function is useful e.g. when you're templating out shell scripts and can't guarantee that the substituted values only contain "shell-safe" strings.
My question: Is there an equivalent of this written in pure bash with at most coreutils as a dependency? Or perhaps even a bash builtin mechanism I'm not aware of?
Minimal example to show how you would use such a utility (called shlex_quote
here as a placeholder):
generate_greeting_script.sh
:
#!/bin/bash
cat > greet.sh <<HEREDOC
#!/bin/bash
greeting=$(shlex_quote "$1")
echo "\$greeting \$(whoami)!"
HEREDOC
chmod +x greet.sh
$ ./generate_greeting_script.sh "'ello"
$ ./greet.sh
'ello govnah!
Which works just fine with a shlex_quote
utility using Python's shlex.quote
, but having Python as a dependency just for that is overkill.
printf %q
-based ones). Interesting howprintf %q
and${...@Q}
use different approaches to how exactly quoting is performed:'ello there
becomes\'ello\ there
withprintf
but''\''ello there'
with theQ
transformation. I guessprintf
's representation is more "efficient" if there are a lot of quotes, while@Q
does better if there are a lot of spaces. – Apperception