This question is not about how to write a properly escaped string literal. I couldn't find any related question that isn't about how to escape variables for direct consumption within a script or by other programs.My goal is to enable a script to generate other scripts. This is because the tasks in the generated scripts will run anywhere from 0 to n times on another machine, and the data from which they are generated may change before they're run (again), so doing the operations directly, over a network will not work.Given a known variable that may contain special characters such as single quotes, I need to write that out as a fully escaped string literal, e.g. a variable foo containing bar'baz should appear in the generated script as:qux='bar'\''baz'which would be written by appending qux=$foo_esc to the other lines of script. I did it using Perl like this:foo_esc='`perl -pe 's/('\'')/\\1\\\\\\1\\1/' <<<$foo`'but this seems like overkill.I have had no success in doing it with bash alone. I have tried many variations of these:foo_esc='${file//\'/\'\\\'\'}'foo_esc='${file//\'/'\\''}'but either extra slashes appear in the output (when I do echo $foo), or they cause a syntax error (expecting further input if done from the shell).
Escape a variable for use as content of another script
bash;variable;variable substitution;bash expansion
I guess I didn't RTFM. It can be done like so:q_mid=\'\\\'\'foo_esc='${foo//\'/$q_mid}'Then echo $foo_esc gives the expected 'bar'\''baz'