Skip to content

Instantly share code, notes, and snippets.

@2510
Last active December 30, 2024 01:43
Show Gist options
  • Save 2510/d8896efbae6a033977a2e810e2f0db0b to your computer and use it in GitHub Desktop.
Save 2510/d8896efbae6a033977a2e810e2f0db0b to your computer and use it in GitHub Desktop.
quote args and eval
#!/bin/sh
fn()
{
local _first=y
while [ $# -gt 0 ]
do
if [ -z "${_first}" ]; then
echo -n ' '
fi
echo -n "'"
echo -n "$1" | sed -e "s/'/'\\\\''/g"
echo -n "'"
_first=
shift
done
}
printargs()
{
local _index=1
while [ $# -gt 0 ]
do
echo "#${_index}: $1"
_index=$(expr "${_index}" + 1)
shift
done
}
# standard call.
printargs 'a b' 'c "d"' "e 'f'"
# generate quoted string for eval.
args=$(fn 'a b' 'c "d"' "e 'f'")
echo "args: ${args}"
# do eval.
eval "printargs ${args}"
$ sh test.sh
#1: a b
#2: c "d"
#3: e 'f'
args: 'a b' 'c "d"' 'e '\''f'\'''
#1: a b
#2: c "d"
#3: e 'f'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment