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
Jill448
  • 1,745
  • 10
  • 37
  • 62
  • 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. – fedorqui Jun 03 '13 at 15:21
  • possible duplicate of [Shell script: Run function from script over ssh](http://stackoverflow.com/questions/22107610/shell-script-run-function-from-script-over-ssh) – Thomas8 Feb 25 '15 at 07:05

1 Answers1

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.

Marcelo Cerri
  • 162
  • 1
  • 10