Last active
December 30, 2024 01:43
-
-
Save 2510/d8896efbae6a033977a2e810e2f0db0b to your computer and use it in GitHub Desktop.
quote args and eval
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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}" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ 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