Two Modes of Shell Operation
- Interactive Mode
You type commands at a prompt and see immediate feedback. - Non-Interactive Mode
You place commands in a file (a script) and run them all at once.
Interactive shells load initialization files like
~/.bashrc, enabling features such as command history and prompt customization. Non-interactive shells skip most of these initializations.Invoking Interactive vs. Non-Interactive Shells
Interactive Example
Non-Interactive Example
- Create a script
script.sh: - Make it executable and run:
Comparing Shell Modes
| Feature | Interactive Shell | Non-Interactive Shell |
|---|---|---|
| Invocation | Direct terminal prompt | ./script.sh or bash script.sh |
| Input | Keyboard | Script file or piped commands |
| Initialization files | ~/.bashrc, PROMPT_COMMAND | /etc/profile, ~/.bash_profile |
| Common Use Cases | Ad hoc tasks, debugging | Automation, cron jobs, CI/CD |
Prompt Variable (PS1) | Typically set (\u@\h:\w\$ ) | Usually unset |
Why It Matters
Some environment variables and shell behaviors differ between modes:Inspecting PS1
Interactive mode:
show_ps1.sh):
PS1 is unset in non-interactive shells.
Don’t rely on interactive-only variables (like
PS1) in scripts. Always initialize or provide defaults for any environment variable your script requires.Best Practices for Shell Scripts
- Start with a shebang
#!/usr/bin/env bashfor portability. - Use
set -euo pipefailto catch errors early. - Double-quote variable expansions to prevent word splitting:
"$VAR". - Explicitly source files when needed:
- Test scripts in both modes if they must run interactively and non-interactively.