I have a Bash script that needs to be run from an interactive prompt, due to environment variables and configuration that only seems to be read when actually logged into a session. Examples below:


me@client:~$ ssh box
user@box:~$ /usr/local/bin/myscript


me@client:~$ ssh box "/usr/local/bin/myscript"

Is there any Bash-fu that I can use in my script to determine if it's being run via a one-line SSH command?


You could just check whether there is a terminal connected to standard input (that's what the tty command does). Add these lines to your script:

if ! tty >/dev/null; then
    echo "Must be run from a tty"
    exit 1

Your script will now exit with an error unless run correctly:

$ ssh badabing ~/scripts/a.sh
Must be run from a tty

$ ssh badabing
terdon@badabing ~ $ ~/scripts/a.sh
| improve this answer | |
  • 2
    In this case, OP's script probably wants ~/.profile etc. to be read. – muru Feb 4 '16 at 14:19
  • 1
    @muru yes, I know, and had even written a first draft of this answer suggesting they just add . ~/.profile to the script, but that could cause other problems. For example, what if ~/.profile sources .bashrc and .bashrc sources a third file that sets up the environment? In that case, assuming the .bashrc is exiting on non-interactive shells, the same problem would occur. It's probably worth posting an answer suggesting the OP source whatever files are necessary but I felt this was both cleaner and actually answers the question asked. – terdon Feb 4 '16 at 14:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.