Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Here document as an argument to bash function

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.

like image 667
Niebelung Avatar asked Jan 12 '11 00:01

Niebelung


People also ask

How do you pass an argument to a function in bash?

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 …

What is a here document in bash?

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.

What is a here document in shell script?

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.

Can bash functions take arguments?

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


2 Answers

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.

like image 136
Robokop Avatar answered Sep 28 '22 09:09

Robokop


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 
like image 22
Dennis Williamson Avatar answered Sep 28 '22 08:09

Dennis Williamson