SSH – Sourcing BASH_ENV for non-interactive SSH commands

sshsshd

I'm hoping to get the $BASH_ENV var to source for non-interactive ssh commands.

I do see my BASH_ENV:

ssh server.example.com env | grep BASH
BASH_ENV=/tmp/set_bash_env_profile

If I do simple ssh login, and env | wc -l I get 85, thanks to $BASH_ENV env var, but if:

ssh server.example.com env | wc -l
17

I get just 17…

I tried ForceCommand in the sshd_config as described here but in my case, the SSH_ORIGINAL_COMMAND is not being set.

Best Answer

Presumably you're setting BASH_ENV in your .bashrc. Bash loads .bashrc when it's interactive and not a login shell, or when it's a login shell that's invoked by rshd or (in many distributions, but it's a compile-time option) sshd. That's too late for this instance of bash. Put the commands directly in ~/.bashrc.

# .bashrc
if [[ $- = *i* ]]; then
  # Commands for interactive use: prompt, aliases, key bindings, etc.
  # Don't set environment variables here, that goes in .profile.
else
  # Commands executed only on remote logins.
  # You can set environment variables here. Do not output anything.
fi

If you only need to set environment variables, you can use ~/.pam_environment instead, which is used for any kind of login. See What's the best distro/shell-agnostic way to set environment variables?

For other ways to execute commands when logging in non-interactively over SSH, see sh startup files over ssh

Related Question