1

I have a function that needs to be sourced when I connect with my server in a non-interactive shell but it seems that no place fits.

I would like to be able to do this

ssh user@remote.com 'my_function'

I read Why does an SSH remote command get fewer environment variables then when run manually? and found that if I put a variable (like hi='hello') in my ~/.ssh/environment file I was able to do this

ssh user@remote.com 'echo ${hi}'

and it would echo my 'hello' value and I was a little bit happy; however, I am not able to put function into the ~/.ssh/environment file since it is not that kind of file :)

Now, where can I put my

function hi {
    echo 'this is a function'
}

so that it will be sourced during a non-interactive shell?

then I could do

ssh user@remote 'hi'

and it would output 'this is a function'

Community
  • 1
  • 1
bjorgvin
  • 103
  • 10
  • You need to put the function in the server as it will be executed there via ssh... and call the full path of the function... – iamauser Sep 28 '13 at 14:14

1 Answers1

0

If you put the function into your shell's rc file, then it depends on your shell. If it's bash, see this:

https://www.gnu.org/software/bash/manual/html_node/Bash-Startup-Files.html

The simplest solution is to put your function into a separate file somewhere in your home, and then source it before you call the function:

ssh user@remote.com '. ~/.my_functions.sh; my_function'

This should work independent of you invoking it from an interactive session or not.

ldx
  • 3,984
  • 23
  • 28
  • ok, this works; however, when I use alias in my sh file they are not available to my non-interactive shell? but it works. – bjorgvin Sep 28 '13 at 19:58
  • even if this works the point is actually not having to set the script in my ssh command. I have added BASH_ENV='$HOME/script.sh' to my ~/.ssh/environment file and it does not seem to be sourced. Is there something I'm missing because this script should be sourced every time – bjorgvin Sep 28 '13 at 20:15
  • When I try ssh user@server.com 'if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi' I get bash: '$HOME/script.sh': No such file or directory – bjorgvin Sep 28 '13 at 20:52
  • well... I found a way to do this with the help of [superuser.com](http://superuser.com/questions/130192/how-do-i-permanently-set-my-bashrc-changes) :) there I found that I could put [ -f $HOME/script.sh ] && . $HOME/script.sh to my /etc/profile and my script was sourced :) – bjorgvin Sep 28 '13 at 21:20