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
bar'baz should appear in the generated script as:
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/g' <<<"$foo"`'"
but this seems like overkill.
I have had no success in doing it with bash alone. I have tried many variations of these:
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).