3

I Have shell script with few functions. I need to run this on 2 different machines for n number of times. Can I call the function as mentioned below and execute it? Or is there any other way to do it?

#!/usr/bash

execCommand () {
  #few statements here
}

getStatus() {
  #few statements here
}

main () {
  execCommand
  getStatus
}

$machine1="machine1"
$machine2="machine2"
$user="username"
$n=2

while [$n -le 2]
 do
   ssh $user@$machine1 'main'
   sleep 100
    ssh $user@$machine2 'main'
    n=$n+1
 done
2
  • The remote machine will not know the function main. You have to send everything through the ssh connection. You can also copy the files to the remote machine and then ssh to execute it. Commented Jun 3, 2013 at 15:21
  • possible duplicate of Shell script: Run function from script over ssh Commented Feb 25, 2015 at 7:05

1 Answer 1

3

There's no straightforward way to do that. But you can extract all the function definitions and inject them as a command at the beginning of your remote command:

ssh "$user@$machine1" "$(declare -f); main"

Notice that you still might have problems with global variables and other resources.

Sign up to request clarification or add additional context in comments.

1 Comment

You can also pass a single function definition with $(declare -f funcname)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.