Sample Header Ad - 728x90

Escape a variable for use as content of another script

72 votes
7 answers
170620 views
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/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: 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).
Asked by Walf (1567 rep)
Jul 18, 2017, 05:14 AM
Last activity: Sep 12, 2024, 05:46 AM