How to run a bash function() in a remote host? in

2019-05-21 05:54发布

问题:

This question already has an answer here:

  • Shell script: Run function from script over ssh 3 answers

I am running a bash script, but when I try to run functions on a remote machine, it says

bash: keyConfig: command not found

Here is my script:

keyConfig() {
    sed -i.bak -r "/^$1/s/([^']+')([^']+)('.*)/\1$2\3/" $3
}

remoteExecution() {
    ssh ppuser@10.101.5.91 " keyConfig $1 $2 $4 "
}

remoteExecution

回答1:

Resone for the error:

When you do

ssh ppuser@10.101.5.91 " keyConfig $1 $2 $4 "

You are actually trying to execute a command keyConfig on remote machine 10.101.5.91 Which is certainly not there:

2 Solution for the problem

1) Make a script on remotehost which contains keyConfig code with same name

OR

2) Execute following instead of function

ssh ppuser@10.101.5.91 "sed -i.bak -r "/^$1/s/([^']+')([^']+)('.*)/\1$2\3/" $3"

Please note you may have to add few escape depending on the sed syntax you are using



回答2:

Simple work-around:

remoteExecution() {
    ssh ppuser@10.101.5.91 "`declare -f keyConfig`; keyConfig $1 $2 $4"
}

Here, keyConfig only calls sed command, which is available on remote system. If keyConfig had been calling any local function, then add that function also in declare -f's command line.

This way, the function keyConfig in the local shell gets defined in the remote shell spawned via ssh & then it gets called.



回答3:

keyConfig is not define as a command in the host "10.101.5.91"

You could try to define a bash script which is called keyConfig in the host "10.101.5.91" and add that script in the ppuser PATH.