Skip to content
Advertisement

Environment variables not loaded when executing command via `ssh` on remote machine

I want to write a script that executes several commands on a remote server, which includes executing some applications. The .bashrc file on the remote machine defines the PATH variable so that these applications are under it.

But when I tried to use ssh <host> <command> , it seems that .bashrc was not loaded. ssh <host> 'echo $PATH' only show a few pathes like /usr/bin .

What confused me even more is that, even ssh <host> "source ~/.bashrc; <command>" not worked. ssh <host> 'source ~/.bashrc; echo $PATH' still only printed a few pathes. I checked by ssh <host> 'cat ~/.bashrc' and confirmed that this file does contains all the PATH definition, which was not affected in the environment where the command executed.

Advertisement

Answer

So after two hours of troubleshooting, I finally find the problem. It is because the following command in the beginning of .bashrc .

# If not running interactively, don't do anything
case $- in
    *i*) ;;
      *) return;;
esac

This prevents anything after that being executed in the environment of ssh <host> <command> .

If you have a similar issue try checking the beginning of the .bashrc file.

4 People found this is helpful
Advertisement