• Uncategorized

About linux : Shell-script-Run-function-from-script-over-ssh

Question Detail

Is there any clever way to run a local Bash function on a remote host over ssh?

For example:

#!/bin/bash
#Definition of the function
f () {  ls -l; }

#I want to use the function locally
f

#Execution of the function on the remote machine.
ssh [email protected] f

#Reuse of the same function on another machine.
ssh [email protected] f

Yeah, I know it doesn’t work, but is there a way to achieve this?

Question Answer

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 [email protected] "$(cat); myfn"
typeset -f myfn | ssh [email protected] "$(cat); myfn"

Better yet, why bother with pipe:

ssh [email protected] "$(typeset -f myfn); myfn"

Or you can use a HEREDOC:

ssh [email protected] << 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 [email protected] "$(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.

I personally don’t know the correct answer to your question, but I have a lot of installation scripts that just copy themselves over using ssh.

Have the command copy the file over, load the file functions, run the file functions, and then delete the file.

ssh [email protected] "scp [email protected]:/myFile ; . myFile ; f ; rm Myfile"

Another way:

#!/bin/bash
# Definition of the function
foo () {  ls -l; }

# Use the function locally
foo

# Execution of the function on the remote machine.
ssh [email protected] "$(declare -f foo);foo"

declare -f foo print the definition of function

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.