Link to home
Start Free TrialLog in
Avatar of TruthHunter
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:

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>]
}

Open in new window

Here's what I want to happen.  I want to invoke mycurlfunc with (something like) the following:

mycurlfunc PUT '{"token": "foo"}'

Open in new window

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>]

Open in new window

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"}'

Open in new window

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>]

Open in new window

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
Avatar of woolmilkporc
woolmilkporc
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of TruthHunter
TruthHunter

ASKER

Aha!  That was it!  I'm usually so "eval-averse" that it hadn't crossed my mind to try that.  Once you mentioned it, it was obvious.

So thanks very much, and enjoy the points!  :^)