1

When I run this simple ruby script:

a = `curl localhost`
puts "Result is: #{a}"


=> % Total    % Received % Xferd  Average Speed   Time    Time     Time  CurrentDload  Upload   Total   Spent    Left  Speed
=> 0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--    0curl: (7) Failed to connect to localhost port 80: Connection refused
=> Result is:

See that the result is being printed when the command is ran, and the variable is empty. But if I run any other command in the same format it works as I expect:

a = `ls`
puts "Result is: #{a}"

=> Result is: test.rb

How can I store the results of the first curl command into a variable?

Scotty
  • 455
  • 7
  • 15

1 Answers1

1

From man curl:

curl normally displays a progress meter during operations, this data is displayed to the terminal by default... If you want a progress meter for HTTP POST or PUT requests, you need to redirect the response output to a file, using shell redirect (>), -o, --output or similar.

What happens when using backticks is that it only gets the standard output (stdout) of the command.

If you need the curl output, you could use the -o option, this creates a file containing the output, which you can then use as you need.

`curl localhost -o curl_localhost_output.txt`
puts File.read('path-to-file/curl_localhost_output.txt')

Also exists "a way" to redirect the stderr to stdout, but isn't to stdout but to a file named 1, so you could use curl localhost 2>&1 and store the curl output, without having to create and read a file.

Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
  • Thank you for the explanation. Based on the info you provided I tested ``a = `curl localhost 2>&1` `` which works as I expected without needing to read from file. Can you add this to your answer so I can accept it – Scotty Nov 28 '17 at 00:40
  • `curl -s localhost` will silence the progress meters and will nicely give you just the response body in the stdout. No need for redirection shenanigans. Also, `require 'open-uri'; a = open('http://localhost') { |f| f.read }` is a pure-Ruby equivalent. – Amadan Nov 28 '17 at 00:50
  • Hi @Amadan, I have tried `curl -s localhost`, and this does silence the progress meter, but does not redirect anything to stdout for me – Scotty Nov 28 '17 at 04:48
  • It doesn't redirect - it just prints the URL contents to stdout, as per normal curl behaviour. if you're not getting anything from ``foo = `curl -s localhost` ``, your localhost might not have anything to say :P – Amadan Nov 28 '17 at 04:55
  • Fair enough, I am actually looking to get the response `curl: (52) Empty reply from server` which is getting repressed by `curl -s localhost`, so that solution doesn't work for my case. Sorry I didn't specify that in the original question. – Scotty Nov 28 '17 at 05:15