I have a shell variable (we shall call x
) containing a string with shell meta characters. For example, I might have
abc \"def\'s\" ghi
sh
has functions.
# quote() - Creates a shell literal
# Usage: printf '%s\n' "...$( quote "..." )..."
quote() {
printf \'
printf %s "$1" | sed "s/'/'\\\\''/g"
printf \'
}
Testing:
$ x='abc "def'\''s" ghi'
$ printf '%s\n' "$x"
abc "def's" ghi
$ printf '%s\n' "prog `quote "$x"`"
prog 'abc "def'\''s" ghi'
$ printf '%s\n' "prog $( quote "`pwd`" )"
prog '/home/ikegami/foo bar'
$ printf '%s\n' "$( quote "a'b" )"
'a'\''b'
$ printf '%s\n' "$( quote '-n' )"
'-n'
$ printf '%s\n' "$( quote '\\' )"
'\\'
$ printf '%s\n' "$( quote 'foo
bar' )"
'foo
bar'
A version that takes multiple arguments:
# quote() - Creates a shell literal
# Usage: printf '%s\n' "$( quote "..." "..." "..." )"
quote() {
local prefix=''
local p
for p in "$@" ; do
printf "$prefix"\'
printf %s "$p" | sed "s/'/'\\\\''/g"
printf \'
prefix=' '
done
}