3

I'm trying to run a command remotely with SSH, but my problem is that when I do that, my .basrhc doesn't get executed, and so the PATH is all wrong and my script is breaking.

What I'm doing is

ssh www.remotehost.com 'my_command'

I've also tried things like

ssh www.remotehost.com 'source ~/.bashrc; my_command' and similar variants, but nothing seems to work.

2 Answers2

12

SSH with a single, simple command argument will not start a shell, which means .bashrc does not get executed.

SSH with a compound command argument such as your second example should start a shell, but it will be a non-interactive one, so that won't run .bashrc by default. See Bash Startup Files in the Bash manual for more information.

However, calling 'source' in your second example command should work. Does your .bashrc have a line like if [ "$PS1" ]; then or if [ -z "$PS1" ]; then at the top? The sample bashrc does have one of these lines, and it prevents the script commands from running unless you are on an interactive shell. As mentioned above, SSH does not start an interactive shell by default when you pass a command argument. Try ssh -t www.remotehost.com 'source ~/.bashrc; my_command', as this will force TTY allocation and act like an interactive shell.

Zanchey
  • 3,051
  • 22
  • 28
  • `if [ "$PS1" ]; then or if [ -z "$PS1" ]; then` did it. In my case it was `[ -z "$PS1" ] && return` just added `source ~/.my_bash_stuff` at the top – natanavra Aug 26 '19 at 13:06
0

Zancheys Post gives you the right solution.

An other aproach could be to provide a simple shell script like following.

#!/bin/sh
# program name: /usr/local/bin/my_command_ssh
#
export PATH=/home/custom/bin:/usr/local/bin:/usr/bin:/bin
my_command

And now you can call it via ssh:

ssh -p22 user@www.remotehost.com '/usr/local/bin/my_command_ssh'
ThorstenS
  • 3,122
  • 19
  • 21