Posted on 2 minutes read

Genesis

Often when a shell command line start to become a little long, I like to break it down into functions.

But things start to get complicated when it involve a remote host.

It usually involve spawning a remote shell with ssh and then double escaping lot of characters (ssh and remote shell) in order to properly execute commands.

Another solution exist though and it's usage it really simple, just write your commands in a function and pass it's name to a magic wrapper that will on remote host re-export it.

How

Has show in this excellent video, bash has a declare builtin that can re-export local function into string (automatically taking care of escaping).

Thus one can pass these generated string to ssh, so functions are re-exported on remote hosts.

Also bash support nested function, you can create and export namespaces this way:

namespace() {
    func2() {
        ls
    }

    func1() {
        func2
    }

    func1
}

func="namespace"
ssh host "$(declare -f $func;); $func"

Why

bash and ssh are ubiquitous and existed for a long time. Plus the shell will allow you to run virtually anything on the remote system.

Where

You can find an helper function here: shell_utils, you need to copy the function into your ~/.bash_aliases.

It export ssh_exec_func:

do_stuff() {
    echo $1
    hostname
}
ssh_exec_func host -- do_stuff hello

More

Stay tuned for a post that'll push this concept further.