Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run curl in bash script and keep the result in a variable [duplicate]

Tags:

bash

curl

This should have been easy but for some reason it's not:

Trying to run a simple curl command, get it's output, and do stuff with it.

cmd='curl -v -H "A: B" http://stackoverflow.com'
result=`$cmd | grep "A:"`
...

The problem - the header "A: B" is not sent.

The execution of the curl command seems to ignore the header argument, and run curl twice - second time with "B" as host (which obviously fail).

Any idea?

like image 523
Elad Tabak Avatar asked Dec 11 '22 12:12

Elad Tabak


1 Answers

Your problem here is that all you are doing on the first command is just setting cmd to equal a string.

Try using $(...) to execute the actual command like so:

cmd=$(curl -v -H "A: B" http://stackoverflow.com)

The result of this will be the actual output from with curl request.

This has been answered many-times see here for example Set variable to result of terminal command (Bash)

like image 132
Blakey Avatar answered May 25 '23 08:05

Blakey