Bash equivalent of Python's shlex.quote
Solution 1:
Since you refer to bash, you can use the bash specific format character "q" in printf
:
$ printf '%q\n' "The world is fuiled by \$s isn't it?"
The\ world\ is\ fuiled\ by\ \$s\ isn\'t\ it\?
From the documentation on bash:
%q
Causes printf to output the corresponding argument in a format that can be reused as shell input.
https://www.gnu.org/software/bash/manual/html_node/Bash-Builtins.html
Solution 2:
Or using @Q
variable expansion
cat generate_greeting_script
:
#!/usr/bin/env bash
cat >greet <<HEREDOC
#!/usr/bin/env bash
printf ${1@Q}' %s!\n' "\$USER"
HEREDOC
chmod +x greet
./generate_greeting_script 'I say hello to'
A .sh
extension on executable scripts with a shebang is not required.
Generated greet
:
#!/usr/bin/env bash
printf 'I say hello to'' %s!\n' "$USER"
Output:
./greet
I say hello to lea!
Reference man bash
:
${parameter@operator}
Parameter transformation.
The expansion is either a transformation of the value of parameter or information about parameter itself, depending on the value of operator. Each operator is a single letter:
Q
The expansion is a string that is the value of parameter quoted in a format that can be reused as input.
Solution 3:
I think you're looking Bash-specific printf %q
format specifier:
$ read && printf "%q\n" "$REPLY"
"very*complicated_&&;$stuff--string'""""'"<<!!
\"very\*complicated_\&\&\;\$stuff--string\'\"\"\"\"\'\"\<\<\!\!
$ echo \"very\*complicated_\&\&\;\$stuff--string\'\"\"\"\"\'\"\<\<\!\!
"very*complicated_&&;$stuff--string'""""'"<<!!