Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use variables from prompt in bash curl command?

Tags:

bash

curl

I am trying to write a script that will setup a Rackspace cloud server and i'm having trouble with one aspect of it. When the script runs it will ask the user a couple questions to get the username and api key. I then use those values in a curl command. The output of the curl command needs to get assigned to a variable as well. This is what i have - i'm thinking there is just a syntax error i am missing. This isn't the whole script, it's just the only part i am having trouble with.

#!/bin/bash

# Ask questions to get login creds
read -p "Rackspace Username? " username
read -p "Rackspace API Key? " apikey

# Get Rackspace token
echo "Getting token..."
token=$(curl -s -X POST https://auth.api.rackspacecloud.com/v2.0/tokens \
    -d '{ "auth":{ "RAX-KSKEY:apiKeyCredentials":{ "username":"$username", "apiKey":"$apikey" } } }' \
    -H "Content-type: application/json" \
    | python -mjson.tool \
    | python -c 'import sys, json; print json.load(sys.stdin)["access"]["token"]["id"]')
echo "...done!"

.....
like image 889
ryanpitts1 Avatar asked Dec 06 '25 02:12

ryanpitts1


1 Answers

The problem with the below line is that $username and $apikey are inside single-quotes and bash variables are not evaluated inside single-quotes:

-d '{ "auth":{ "RAX-KSKEY:apiKeyCredentials":{ "username":"$username", "apiKey":"$apikey" } } }' \

To fix it, end the single-quote string before the bash variable and start it again afterwards:

-d '{ "auth":{ "RAX-KSKEY:apiKeyCredentials":{ "username":'"$username"', "apiKey":'"$apikey"' } } }' \

If you need the literal double-quotes in the string for it to work, then we have to add them in inside the single-quoted portion of the string:

-d '{ "auth":{ "RAX-KSKEY:apiKeyCredentials":{ "username":"'"$username"'", "apiKey":"'"$apikey"'" } } }' \
like image 152
John1024 Avatar answered Dec 09 '25 05:12

John1024