Here document as an argument to bash function

Niebelung  picture Niebelung · Jan 12, 2011 · Viewed 14.5k times · Source

Is it possible to pass a here document as a bash function argument, and in the function have the parameter preserved as a multi-lined variable?

Something along the following lines:

function printArgs {
echo arg1="$1"
echo -n arg2=
cat <<EOF
$2
EOF
}

printArgs 17 <<EOF
18
19
EOF

or maybe:

printArgs 17 $(cat <<EOF
18
19
EOF)

I have a here document that I want to feed to ssh as the commands to execute, and the ssh session is called from a bash function.

Answer

Robokop picture Robokop · Jan 12, 2011

The way to that would be possible is:

printArgs 17 "$(cat <<EOF
18
19
EOF
)"

But why would you want to use a heredoc for this? heredoc is treated as a file in the arguments so you have to (ab)use cat to get the contents of the file, why not just do something like:

print Args 17 "18
19"

Please keep in mind that it is better to make a script on the machine you want to ssh to and run that then trying some hack like this because bash will still expand variables and such in your multiline argument.