PIppo
PIppo

Reputation: 113

How I get the HTTP responses from bash script with curl command?

I have the following command that I execute from the shell:

curl -v -s -X GET -H "UserName: myUsername" -H "Password: myPassword" 
https://example.com

and from terminal I have the HTTP/1.1 200 response with different response parameters:

HTTP/1.1 200 OK
Date: Fri, 23 Oct 2015 10:04:02 GMT
Name: myName
Age: myAge

...

Now, in my .sh file i want take name and age so have the values in my variables $name and $age. My initial idea was to redirect stdout to a file to parse:

curl -v -s -X GET -H "UserName: myUsername" -H "Password: myPassword"
https://example.com > out.txt

but the file is empty.

Some ideas to have a variables in bash script enhanced by the HTTP response?

EDIT: the variables that I want to take are in the header of the response

Thanks

Upvotes: 9

Views: 30640

Answers (3)

PIppo
PIppo

Reputation: 113

I resolved:

header=$(curl -v -I -s -X GET -H "UserName: myUserName" -H "Password: 
myPassword" https://example.com)

name=`echo "$header" | grep name`
name=`echo ${name:4}`
age=`echo "$header" | grep age`
age=`echo ${age:3}`

Upvotes: 2

christophetd
christophetd

Reputation: 3874

You can make use of the grep and cut command to get what you want.

response=$(curl -i http://yourwebsite.com/xxx.php -H ... 2>/dev/null)
name=$(echo "$response" | grep Name | cut -d ':' -f2)
age=$(echo "$response" | grep MyAge | cut -d ':' -f2)

I changed Age to MyAge : Age is a standard HTTP header and it is not a good idea to risk to overwrite it.

Upvotes: 2

Angel O'Sphere
Angel O'Sphere

Reputation: 2666

You have to add --write-out '%{http_code}' to the command line and curl will print the HTTP_CODE to stdout.

e.g.curl --silent --show-error --head http://some.url.com --user user:passwd --write-out '%{http_code}'

However I don't know all the other "variables" you can print out.

Upvotes: 8

Related Questions