2

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:

Good

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

Bad

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?

Craig Watson
  • 279
  • 1
  • 5

1 Answers1

2

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
fi

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
Works!
terdon
  • 234,489
  • 66
  • 447
  • 667
  • 2
    In this case, OP's script probably wants `~/.profile` etc. to be read. – muru Feb 04 '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](http://unix.stackexchange.com/q/257571/22222), 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 04 '16 at 14:22