Command not found with "ssh host command" but it works after logging in: PATH and .bashrc
ssh host command runs a non-interactive shell that skips .profile and most of .bashrc, so PATH is shorter. Use a full path, move the PATH line or run bash -lc.
A program runs fine when you log in and type its name, but fails when you run it in one go:
$ ssh [email protected] mytool --version
bash: line 1: mytool: command not found
The program is there. The shell that runs it has a different PATH.
Two kinds of shell
- When you log in with
ssh host, sshd starts your shell as an interactive login shell. Bash reads/etc/profileand then the first of~/.bash_profile,~/.bash_loginor~/.profileit finds, and those usually read~/.bashrc. - When you run
ssh host command, sshd starts your shell to run that one command. It is neither a login shell nor interactive, so the profile files are not read.
The Bash manual adds one special case: when Bash can tell that sshd started it to run a command, it reads ~/.bashrc. But the ~/.bashrc that Debian and Ubuntu put in new home folders starts with this:
# If not running interactively, don't do anything
case $- in
*i*) ;;
*) return;;
esac
So any export PATH=... line further down never runs for ssh host command. What is left is the default PATH that sshd sets, for example /usr/local/bin:/usr/bin:/bin:/usr/games on Debian. Programs in ~/bin, ~/.local/bin, /opt/... or a language's own folder are not found.
See the difference
Quote the command in single quotes so $PATH is expanded on the host, not on your side:
ssh [email protected] 'echo $PATH'
Compare it with echo $PATH after a normal login.
Fixes
Pick one:
- Use the full path in the command:
ssh host /opt/mytool/bin/mytool --version. Find it after a normal login withcommand -v mytool. - Set PATH before the interactive check. Put the
export PATH=...line at the very top of~/.bashrc, above thecase $- inblock. Keep that part silent: a startup file that prints text breaks SFTP and scp. See SFTP "Received message too long". - Run a login shell for the command:
ssh host 'bash -lc "mytool --version"'.-lmakes Bash read the profile files first. - Ask the administrator. sshd can read
~/.ssh/environmentandenvironment=options inauthorized_keys, but only whenPermitUserEnvironmentis turned on insshd_config. It is off by default.
Adding -t to ssh gives the command a terminal, but the shell is still not a login shell, so it does not change PATH.
The same problem with Mosh
The mosh command logs in with SSH and runs mosh-server as a command, so it hits the same short PATH. That is why mosh-server installed in a home folder or under /opt is reported as not found: see What Mosh needs on the host.
Related
- Check if a shell is running over SSH, inside tmux, or inside screen
- SSH "PTY allocation request failed on channel 0"
- Shell and tmux basics