Search code examples
rubyshellvariablescurlbackticks

Curl command being printed instead of stored in Ruby


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?


Solution

  • 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.