1

I know I can call variables from the local shell in an SSH session, so I assumed I could call a function this way too. But this doesn't seem to work.

I have a script that checks if my local machine can handle certain operations and if it can I need to call local functions, if the local machine cannot I need to SSH into a remote machine and call the local functions.

canHandle() {
  if [ -d /this_must_exist/ ]
  then
     return 0
  else
     return 1
  fi
}

localFunction() {
  // Predefined tasks
}

canHandle
if [ $? -eq 0 ]
then
   // Process locally using predefined functions
   localFunction
else
   ssh -t me@server << ENDSSH
   // Process remotely calling predefined local functions
   localFunction
   ENDSSH
fi 
nullByteMe
  • 6,141
  • 13
  • 62
  • 99
  • 1
    Possible duplicate of [Shell script: Run function from script over ssh](http://stackoverflow.com/questions/22107610/shell-script-run-function-from-script-over-ssh) – RASG Mar 21 '17 at 20:56

2 Answers2

3

Imho this will not work.

Local Variables get expanded on your Local Shell, and are Transferred expanded.

You could write a bash script doing the same as local function, and write a function to copy it via scp to the remote system, execute it there via shh and delete it afterwards.

MyChaOS
  • 332
  • 1
  • 4
  • hmm... I feel like there must be a way. Perhaps somehow echoing my function and doing and `eval` on the server. idk, I just feel like this should be possible without the duplication! – nullByteMe Aug 28 '13 at 14:15
  • 1
    a somehow messy way to echo the function is: ``echo function `type local_function | tail -n +2` `` – MyChaOS Aug 28 '13 at 14:29
0

You can declare and run a locally defined Bash function greet on a remote machine myhost like so:

greet() { echo "Hello, $1"; }
ssh myhost "$(declare -f greet); greet 'friend'"

The Bash builtin declare -f prints the source code of the passed function.