Let's say you have a Bash shell script, and you need to run a series of operations on another system (such as via ssh). There are a couple of ways to do this.
First, you can stage a child script on the remote system, then call it, passing along appropriate parameters. The problem with this is you will need to manually keep the remote script updated whenever you change it -- could be a bit of a challenge when you have something to execute on a number of remote servers (i.e., you have a backup script running on a central host, and it needs to put remote databases in hot backup mode before backing them up).
Another option is to embed the commands you want to run remotely within the ssh command line. But then you run into issues with escaping special characters, quoting, etc. This is ok if you only have a couple commands to run, but if it is a complex piece of Bash code, it can get a bit unwieldy.
So, to solve this, you can use a technique called rpcsh -- rpc in shell script, as follows:
First, place the remote code segment into a shell function:
hello() {
echo "Hello, world, I'm coming from $(uname -n)."
}
Now, using "$(declare -f)", you can push this function to a remote host and execute it via ssh, as follows:
ssh user@rmthost "$(declare -f hello); hello"
Output:
Hello, world, I'm coming from rmthost.
Bash will take care of all the escaping and quoting, load the function up, and leave the function in the environment to be executed. You can also push variables and arrays over, using "$(declare -p varname)
". You can also list multiple functions and variables, if the main function relies on them, by listing them individually.
To make this more automatic, check out the attached rpcsh() function.