5

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?

Elad Tabak
  • 2,317
  • 4
  • 23
  • 33
  • Am not sure of the issue you are seeing? What is your expected output? – Inian Feb 15 '17 at 09:31
  • @elad-tabak I would suggest that you should always check the result of the command like I suggested before storing the same in any variable. This will help you find where the issue lies exactly – Karan Shah Feb 15 '17 at 09:38

2 Answers2

10

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)

Community
  • 1
  • 1
Blakey
  • 803
  • 7
  • 15
5

Keep in mind that cURL debug output is redirected to STDERR - this is so you can pipe the output to another program without the information clobbering the input of the pipe.

Redirect STDERR to STDOUT with the --stderr - flag like so:

cmd="curl -s -v http://stackoverflow.com -H 'Test:1234' --stderr -"
result=`$cmd | grep "Test:"`
echo $result

./stackoverflow.sh 
> 'Test:1234'
Michael
  • 76
  • 3