Shell script: Run function from script over ssh

You can use the typeset command to make your functions available on a remote machine via ssh. There are several options depending on how you want to run your remote script.

#!/bin/bash
# Define your function
myfn () {  ls -l; }

To use the function on the remote hosts:

typeset -f myfn | ssh user@host "$(cat); myfn"
typeset -f myfn | ssh user@host2 "$(cat); myfn"

Better yet, why bother with pipe:

ssh user@host "$(typeset -f myfn); myfn"

Or you can use a HEREDOC:

ssh user@host << EOF
    $(typeset -f myfn)
    myfn
EOF

If you want to send all the functions defined within the script, not just myfn, just use typeset -f like so:

ssh user@host "$(typeset -f); myfn"

Explanation

typeset -f myfn will display the definition of myfn.

cat will receive the definition of the function as a text and $() will execute it in the current shell which will become a defined function in the remote shell. Finally the function can be executed.

The last code will put the definition of the functions inline before ssh execution.

Leave a Comment