Determining If You Are Running Interactively

Problem

You have some code you want to run only if you are (or are not) running interactively.

Solution

Use the following case statement:

#!/usr/bin/env bash
# cookbook filename: interactive

case "$-" in
    *i*) # Code for interactive shell here
         ;;
    *)   # Code for non-interactive shell here
         ;;
esac

Discussion

$- is a string listing of all the current shell option flags. It will contain i if the shell is interactive.

You may also see code like the following (this will work, but the solution above is the preferred method):

if [ "$PS1" ]; then
    echo This shell is interactive
else
    echo This shell is not interactive
fi

See Also

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.