Interactive vs. Non-Interactive Bash
Bash runs in two different modes. An interactive shell talks to a person: it prints a prompt, lets you edit the command line, remembers history, and manages jobs. A non-interactive shell runs commands from a script, from a -c string or from a pipe, with no person typing. It is the same program in both cases, but several features are switched on or off depending on the mode, and some errors are handled differently.
Knowing the difference explains many puzzles: why an alias works at the prompt but not in a script, why ! sometimes produces "event not found", why kill $$ ends a script but not your terminal, and why a script that asks a question can hang in a cron job. This lesson shows how Bash decides which mode it is in, what changes between the modes, and how a script can adapt to the way it is run.
How Bash Decides
According to the Bash manual, a shell is interactive when either:
- it was started without a script file name and without
-c, and both its standard input and its standard error are connected to a terminal, or - it was started with the
-ioption.
Everything else is non-interactive: running a script (bash script.sh or ./script.sh), bash -c 'commands', and a shell reading commands from a pipe or a file.
Detecting the Mode with $-
The special parameter $- contains the letters of the shell's current single-letter options. The letter i appears only in an interactive shell. This test script also checks PS1 and whether standard input and standard output are terminals (-t FD is true when the file descriptor is connected to a terminal):
# flags.sh
echo "script: \$-=$- PS1=${PS1-<unset>}"
[[ $- == *i* ]] && echo "interactive" || echo "not interactive"
[[ -t 0 ]] && echo "stdin is a terminal" || echo "stdin is not a terminal"
[[ -t 1 ]] && echo "stdout is a terminal" || echo "stdout is not a terminal"
Running the script and some other non-interactive forms from a test program (no terminal involved):
bash flags.sh
bash -c 'echo "bash -c: \$-=$- PS1=${PS1-<unset>}"'
echo 'echo "piped: \$-=$-"' | bash
echo 'echo "bash -s: \$-=$- args=$*"' | bash -s one two
script: $-=hB PS1=<unset>
not interactive
stdin is not a terminal
stdout is not a terminal
bash -c: $-=hBc PS1=<unset>
piped: $-=hBs
bash -s: $-=hBs args=one two
None of these shells contains i, and none has a PS1, because Bash sets a default prompt only in interactive shells. The letter c marks a shell started with -c, and s a shell reading commands from standard input (-s lets you pass arguments to such a shell). h (remember command locations) and B (brace expansion) are on in every Bash by default.
The same checks inside a terminal:
$ echo "interactive: $-"; echo "PS1=$PS1"
interactive: himBHs
PS1=$
$ bash flags.sh
script: $-=hB PS1=<unset>
not interactive
stdin is a terminal
stdout is a terminal
$ bash flags.sh < /dev/null | cat
script: $-=hB PS1=<unset>
not interactive
stdin is not a terminal
stdout is not a terminal
$ bash -i -c 'echo "bash -i -c: $-"'
bash -i -c: himBHc
The interactive shell has i, plus m (job control, called monitor mode) and H (history expansion with !). The script started from that terminal is still non-interactive, even though its input and output were the terminal. This distinction matters:
| Question | Test | Use it for |
|---|---|---|
| Is this shell interactive? | [[ $- == *i* ]] | startup files such as ~/.bashrc |
| Can I ask the user a question? | [[ -t 0 ]] | scripts that may prompt |
| Is the output going to a screen? | [[ -t 1 ]] | colors, progress bars, column layout |
A script is never interactive in the shell sense, but it may very well have a person at the keyboard. Scripts should therefore test the file descriptors, not $-. Older startup files sometimes test [ -z "$PS1" ] instead of $-; it works because only interactive shells set PS1, but $- states the intention directly.
-i forces interactive mode, as bash -i -c shows; when not connected to a terminal, such a shell prints warnings about job control.
Redirections Change the Mode
Because the rule involves standard input and standard error, redirecting either of them when starting bash from a prompt gives a non-interactive shell:
$ echo 'echo "inner: $-"' | bash
inner: hBs
$ bash 2>/dev/null
echo "inner: $-"
inner: hBs
exit
The second inner shell printed no prompt: with standard error sent to /dev/null, it did not count as interactive, read the typed lines as a script, and showed no prompt (the typed lines are visible only because the terminal echoes what you type).
What Changes Between the Modes
| Feature | Interactive | Non-interactive |
|---|---|---|
Prompt (PS1, PS2) | printed | not used |
| Startup files | ~/.bashrc (or the login files) | only $BASH_ENV (lesson 146) |
| Line editing (Readline) and tab completion | on | off |
Command history and ! expansion | on (H in $-) | off |
Job control ([1] 1234, fg, bg) | on (m in $-) | off |
| Alias expansion | on | off unless shopt -s expand_aliases (lesson 144) |
Errors such as ${var:?} on an unset variable | report, keep the shell | stop the script |
SIGTERM (plain kill) | ignored by the shell | ends the shell |
SIGINT (Ctrl+C) | cancels the current line | ends the script (lesson 141) |
exit | closes the terminal window or session | ends the script |
Fatal Errors Only in Scripts
Some errors make a non-interactive shell stop, while an interactive shell reports them and continues. A script that uses ${missing:?} on an unset variable (lesson 45):
# diff.sh
echo "start"
echo "${missing:?is not set}"
echo "after the error"
start
diff.sh: line 2: missing: is not set
status 1
The script ended at line 2 with status 1. The same expansion typed at the prompt:
$ echo "${missing:?is not set}"
bash: missing: is not set
$ echo "shell still here: $?"
shell still here: 1
The interactive shell kept running. This design protects your session: a typing mistake must not close your terminal, while a script that hits a serious error should stop rather than continue with wrong data.
History Expansion and Signals
A script and an interactive shell treat ! and kill $$ differently. The script:
# diff2.sh
echo hello!world
echo "pid $$"; kill $$; echo "still running after kill"
hello!world
pid 501
Terminated
status 143
In the script, ! is an ordinary character, and kill $$ (which sends SIGTERM to the shell itself) ended it with status 143 (128 + 15). The Terminated line was printed by the shell that started the script. At the prompt:
$ echo hello!world
bash: !world: event not found
$ kill $$; echo "survived kill: $$"
survived kill: 506
The interactive shell tried to expand !world as a reference to an earlier command in the history (lesson 46 shows how to quote !), and it ignored SIGTERM, so kill $$ did nothing. To end an interactive shell from outside, kill -HUP (what a closing terminal window sends) or kill -KILL is needed.
Job Control and Prompts from read
# diff3.sh
sleep 1 &
echo "job started"
read -r -p "Name: " name
echo "name=[$name]"
With the input piped in, no terminal involved:
echo Ana | bash diff3.sh
job started
name=[Ana]
Run from the interactive shell, with the name typed at the keyboard:
$ sleep 1 &
[1] 508
$ bash diff3.sh
job started
Name: Ana
name=[Ana]
[1]+ Done sleep 1
The interactive shell printed the job number and PID for sleep 1 & and later reported Done; the script started its own background sleep silently. read -p showed its prompt only when the input came from a terminal: with piped input, no Name: appeared. Bash does this on purpose, because a prompt is pointless when nobody is typing.
Writing Scripts That Work in Both Situations
A script may be started by a person in a terminal, by another script, by cron, or by a CI system. The person can answer questions and enjoys colors; the automated run cannot answer and should produce clean text. Two tests make the difference visible:
[[ -t 0 ]]: ask questions only when standard input is a terminal; otherwise take the data from arguments, standard input or defaults.[[ -t 1 ]]: use colors only when standard output is a terminal, so that log files and pipes do not receive escape codes.
When nobody is typing, a question cannot be answered: with input from /dev/null, read fails at once and the script continues with an empty answer, and with input from a pipe, read silently takes a line that was meant as data. Checking -t 0 first lets the script choose a sensible behavior instead.
A Complete Example: A Note Taker That Adapts to Its Caller
newnote.sh appends a dated note to a notes file. A person can run it without arguments and type the note; a script can pass the text as arguments or pipe it in.
#!/usr/bin/env bash
# newnote.sh: add a dated note to a notes file.
# newnote.sh TEXT... note text from the arguments
# newnote.sh asks for the text when a person is typing,
# reads it from standard input otherwise
set -euo pipefail
notes=${NOTES_FILE:-$HOME/notes.txt}
if (( $# > 0 )); then
text="$*"
elif [[ -t 0 ]]; then # standard input is a terminal: ask
read -r -p "Note: " text || text=
else # piped or redirected: read it all
text=$(cat)
fi
text=${text//$'\n'/ } # several input lines become one note
if [[ -z ${text//[[:space:]]/} ]]; then
echo "newnote: empty note, nothing saved" >&2
exit 1
fi
# Colors only when the output goes to a terminal, never into files or pipes
if [[ -t 1 ]]; then
ok=$'\e[32m' off=$'\e[0m'
else
ok= off=
fi
printf '%s %s\n' "$(date +%F)" "$text" >> "$notes"
printf '%sSaved%s to %s (%d in total)\n' "$ok" "$off" "$notes" "$(wc -l < "$notes")"
How It Works
- Arguments come first. If any were given, they are the note, whatever the input is connected to.
"$*"joins them with spaces. [[ -t 0 ]]decides between asking and reading. Only when a person is at the keyboard does the script printNote:and wait.|| text=handles Ctrl+D:readthen fails, which would stop the script underset -e; instead the note becomes empty and is rejected below.text=$(cat)reads everything that was piped or redirected in, and${text//$'\n'/ }replaces the newlines, so a multi-line message becomes one note line.- The empty check removes all whitespace with
${text//[[:space:]]/}and rejects the note if nothing is left. The message goes to standard error and the status is 1, so a calling script can detect the failure. [[ -t 1 ]]switches the green color codes on only for a terminal. When the output is redirected to a log file or a pipe, the variables are empty and the line is plain text.NOTES_FILElets the caller choose another notes file through the environment, with~/notes.txtas the default (lesson 45).
Running the Complete Example
In an interactive terminal (in the real terminal, the word Saved appears in green):
$ ./newnote.sh
Note: Call the plumber
Saved to /home/ana/notes.txt (1 in total)
$ ./newnote.sh Renew domain gocourse
Saved to /home/ana/notes.txt (2 in total)
$ ./newnote.sh | cat -v
Note: Order printer paper
Saved to /home/ana/notes.txt (3 in total)
$ ./newnote.sh
Note:
newnote: empty note, nothing saved
The third run shows that input and output are independent: the input was still the keyboard, so the script asked, but the output went through a pipe, so cat -v (which would display escape characters as ^[) shows no color codes. In the last run, Enter was pressed without text.
Non-interactive callers:
printf 'Backup finished\nall 3 servers\n' | ./newnote.sh
./newnote.sh < /dev/null; echo "status $?"
./newnote.sh "Weekly report sent" < /dev/null > out.log; cat -v out.log
Saved to /home/ana/notes.txt (4 in total)
newnote: empty note, nothing saved
status 1
Saved to /home/ana/notes.txt (5 in total)
The piped text was read without a prompt and joined into one line. Empty redirected input was rejected with status 1 instead of hanging or saving a blank note. The last command imitates a cron job: arguments, no input and output to a file, which received plain text. The notes file afterwards:
2026-11-24 Call the plumber
2026-11-24 Renew domain gocourse
2026-11-24 Order printer paper
2026-11-24 Backup finished all 3 servers
2026-11-24 Weekly report sent