Skip to main content

How to determine within a startup script whether or not Bash is running interactively, or from a Terminal.

#!/usr/bin/env bash

#
# Test the value of the '-' special parameter.
# It contains "i" when the shell is interactive:
case "$-" in
    *i*) echo This shell is interactive ;;
    *) echo This shell is not interactive ;;
esac

#
# Alternatively, startup scripts may examine the variable PS1;
# it is unset in non-interactive shells, and set in interactive shells:
if [ -z "$PS1" ]; then
    echo This shell is not interactive
else
    echo This shell is interactive
fi

#
# Check if a running from a Terminal (https://serverfault.com/a/753459)
if [ -t 0 ]; then
    echo stdin is a terminal
else
    echo stdin is not a terminal
fi