Testing for a non-interactive shell

I had some backup scripts that used ssh and scp but reported the following warning to stderr:

stdin: is not a tty

If you receive this error then it’s likely that your .bashrc file (or another terminal init file, on the server side) is trying to do things that require an interactive shell i.e. a shell which is expecting commands to be typed in.

To get rid of this warning you can add some bash to the top of .bashrc to prevent it doing anything if you’re in a non-interactive shell. There are a few alternatives, of which I’ve tried two:

Test for the ‘i’ flag

If the ‘i’ flag is set in the current shell options, then we have an interactive shell, so if it’s missing then we don’t.

# If 'i' option set then we have non-interactive shell so return
if [[ $- != *i* ]] ; then
	return
fi

Test for the prompt

If there is no prompt variable ‘$PS1’ then we have a non-interactive shell.

# If no prompt then we have non-interactive shell so return
[ -z "$PS1" ] && return

There are more ways of doing this - see the references.

References

Last modified: 19/06/2013 Tags:

This website is a personal resource. Nothing here is guaranteed correct or complete, so use at your own risk and try not to delete the Internet. -Stephan

Site Info

Privacy policy

Go to top