Interactive vs. Non-Interactive Bash

Su Suriya Ravichandran Updated 06 Dec 2026
10 min read ·Lesson 147 of 205

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 -i option.

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:

QuestionTestUse 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

FeatureInteractiveNon-interactive
Prompt (PS1, PS2)printednot used
Startup files~/.bashrc (or the login files)only $BASH_ENV (lesson 146)
Line editing (Readline) and tab completiononoff
Command history and ! expansionon (H in $-)off
Job control ([1] 1234, fg, bg)on (m in $-)off
Alias expansiononoff unless shopt -s expand_aliases (lesson 144)
Errors such as ${var:?} on an unset variablereport, keep the shellstop the script
SIGTERM (plain kill)ignored by the shellends the shell
SIGINT (Ctrl+C)cancels the current lineends the script (lesson 141)
exitcloses the terminal window or sessionends 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 print Note: and wait. || text= handles Ctrl+D: read then fails, which would stop the script under set -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_FILE lets the caller choose another notes file through the environment, with ~/notes.txt as 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

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Interactive vs. Non-Interactive Bash and get answers drawn from it.

Signed-in readers only.