How do I pass a multiline variable as a parameter to a function

Trying to capture and display the output of curl was driving me nuts. I finally found a workaround, but I don't understand why it is needed.

Here's a script that fails:

#!/bin/bash
function echo_output() {
    echo $@
}

CURL_OUTPUT=$(curl -sL --head www.google.com/foobar)
echo_output "$CURL_OUTPUT"

Here's a script that works: (escaping the carriage returns)

#!/bin/bash
function echo_output() {
    OUT="${@//[$'\r']/\r}"
    echo $OUT
}

CURL_OUTPUT=$(curl -sL --head www.google.com/foobar)
echo_output "$CURL_OUTPUT"

What gives? What is special about newlines and "$@"? Thanks for the help.


Solution 1:

I do not think there is anything wrong with $@.

But in the first case in order cleanly output that variable as a parameter you assigned to curl with output having newlines, in your function echo_output() you need to quote the "$@", in this case "echo"(which in turn does only printing its positional arguments into standard output and nothing more) will split the words -> arguments(parameters) correctly. As Dawud mentioned it is better to use printf in this cases.

Again in your case:

function echo_output() {
echo "$@"
}

will do it.