$- variable in Bash shows the current shell’s option flags. These flags differ when you run commands interactively versus inside a script. In this guide, we’ll:
- Inspect
$-interactively - Compare interactive vs. non-interactive outputs
- Demonstrate how
set -eaffects$- - Review common
$-flags in a summary table
Checking $- Interactively
Run the following command in your terminal to see which flags are active in your interactive shell:
h, i, m, B, H, s) represents a specific shell option. These may vary between systems and user configurations.
The exact set of flags depends on your Bash version and how you’ve configured your environment (e.g., via
.bashrc or .bash_profile).Comparing with a Non‐Interactive Script
Create a file namedspecial-dash.sh:
i flag (interactive mode) is missing because scripts run non-interactively by default.
Enabling “Exit on Error” with set -e
The set -e option causes Bash to exit immediately if any command returns a non-zero status. Let’s enable it in our script:
e indicates that “exit on error” is active.
Using
set -e can make debugging harder if you’re not careful. Always test scripts thoroughly or combine with set -u and set -o pipefail for stricter error checking.Common $- Flags
| Flag | Description |
|---|---|
| i | Shell is running in interactive mode |
| e | Exit immediately if a command exits with failure |
| u | Treat unset variables as an error |
| x | Print commands and their arguments as they execute |
Further Reading
By understanding and inspecting the
$- variable, you can better control your shell’s behavior in both interactive sessions and automated scripts.