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.
To pass any number of arguments to the bash function simply put them right after the function's name, separated by a space. It is a good practice to double-quote the arguments to avoid the misparsing of an argument with spaces in it. The passed parameters are $1 , $2 , $3 …
A HereDoc is a multiline string or a file literal for sending input streams to other commands and programs. HereDocs are especially useful when redirecting multiple commands at once, which helps make Bash scripts neater and easier to understand.
Here document (Heredoc) is an input or file stream literal that is treated as a special block of code. This block of code will be passed to a command for processing. Heredoc originates in UNIX shells and can be found in popular Linux shells like sh, tcsh, ksh, bash, zsh, csh.
Instead, Bash functions work like shell commands and expect arguments to be passed to them in the same way one might pass an option to a shell command (e.g. ls -l ). In effect, function arguments in Bash are treated as positional parameters ( $1, $2.. $9, ${10}, ${11} , and so on).
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.
If you're not using something that will absorb standard input, then you will have to supply something that does it:
$ foo () { while read -r line; do var+=$line; done; } $ foo <<EOF a b c EOF
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With