[bash] running a function remotely using ssh

Hi all.

I need a bash script to run a function remotely. I think it should be similar to the following but can't figure out the exact syntax.

Here is the script:

#!/bin/bash

function nu ()
{
        for var in {0..5}; do printf "$var, "; done; echo
}

ssh host "$(typeset -f); nu"

Here is the output:

./r.sh 
Badly placed ()'s.
{: Command not found.
for: Command not found.
do: Command not found.
var: Undefined variable.
done: Command not found.

}: Command not found.
nu: Command not found.

Next step is to run it as other user using su command but this is the start.

Thank you in advanced.

I think you're better off starting with:

ssh host bash -s << 'EOF'
nu() {
  whatever
}
nu
EOF

This starts a remote shell and reads the script from stdin, which you give with a heredoc

Above seems to work between two systems running bash (or sh ) each. What be the shell on the remote system? Do you know if the errors occur on the remote or local host?

As others have pointed out, setting a function on your system doesn't make the function exist on a remote system.

I'll also point out that $(typeset -f) is run on your local system, before ssh is even run. This is because you've put it inside double quotes, which will evaluate variables, backticks, and $( ) before processing the command.

Thank you for all responses.
Using heredoc is the alternative i'm indeed using right now.

I'm trying to find a better way because I have several functions and need to use them locally AND remotely and don't want to declare the functions more than once.

I'm aware that typeset is evaluated locally, otherwise it won't contain the function and in that case is useless

I'm not sure where the error occurs.

How about:

. functions.sh

ssh user@host <<EOF
$(cat functions.sh)

remote code
EOF

It works fine for me here, output:

0, 1, 2, 3, 4, 5,

I expect your remote shell is not a bash shell, if I force csh on remote side:

#!/bin/bash

function nu ()
{
        for var in {0..5}; do printf "$var, "; done; echo
}

ssh host "csh -c \"$(typeset -f); nu\""

I get a very similar output:

Badly placed ()'s.
{: Command not found.
for: Command not found.
do: Command not found.

Perhaps you should force bash on remote side with ssh host "/usr/bin/bash -c \"$(typeset -f); nu\""

Chubler_XL, that's look promising, I already tried a similar thing, but it still output a problem.
I guess that there is something with bash version here
mine:

bash --version
GNU bash, version 3.2.51(1)-release (x86_64-suse-linux-gnu)

new output:

Unmatched ".
{: Command not found.
for: Command not found.
do: Command not found.
var: Undefined variable.
done: Command not found.

Unmatched ".

do u have a workaround for this?

btw, fixed my output in original post.

This works here also.

#!/bin/bash

function nu ()
{
        for var in {0..5}; do printf "$var, "; done; echo
}

ssh host /usr/bin/bash <<EOF
$(typeset -f)
nu
EOF
2 Likes

Genius!
Thank you