TruthHunter
asked on
bash: expanding a variable with embedded quotes
Hi,
I've been wrestling with this for too long, and need help.
I have the following bash shell function to issue a cURL command:
Max points since I'm trying to get this done quickly - I think I'm reasonably close, but just can't find the right combination. Thanks for any help!
I've been wrestling with this for too long, and need help.
I have the following bash shell function to issue a cURL command:
mycurlfunc () {
CMD=GET
HDRS=
BODY=
if [ "$1" = PUT ]; then
CMD=PUT
HDRS='-H '"'"'Content-Type: application/json'"'"
BODY='-d '"'"$2"'"
fi
curl --compressed -k -v -X $CMD $HDRS $BODY [<url>]
}
Here's what I want to happen. I want to invoke mycurlfunc with (something like) the following:mycurlfunc PUT '{"token": "foo"}'
such that $1 = 'PUT' and $2 = '{"token": "foo"}'. I want the HDRS and BODY variables to be expanded/inserted into the curl command so it is issued as follows:curl --compressed -k -v -X PUT -H 'Content-Type: application/json' -d '{"token": "foo"}' [<url>]
When I create HDRS and BODY at the command line they look like the strings I want:$ set -vx
$ HDRS='-H '"'"'Content-Type: application/json'"'"
$ echo $HDRS
echo $HDRS
+ echo -H ''\''Content-Type:' 'application/json'\'''
-H 'Content-Type: application/json'
$ BODY='-d '"'"'{"token": "foo"}'"'"
$ echo $BODY
echo $BODY
+ echo -d ''\''{"token":' '"foo"}'\'''
-d '{"token": "foo"}'
However, when I put them into the curl command, the literal variable values, not "evaluated" values, appear; i.e., the single quotes themselves are being escaped and the string tokens in the variables are being quoted:curl --compressed -k -v -X PUT -H ''\''Content-Type:' 'application/json'\''' -d ''\''{"token":' '"foo"}'\''' [<url>]
My question is simple: How can I set HDRS and BODY up to expand the way I want?Max points since I'm trying to get this done quickly - I think I'm reasonably close, but just can't find the right combination. Thanks for any help!
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
So thanks very much, and enjoy the points! :^)