When writing complex bash scripts or troubleshooting terminal behavior in Linux, you often need to view or temporarily modify the internal settings of your shell environment. While commands like export handle environment variables passed to child processes, the set command is the primary tool used to view and change the internal attributes, options, and local variables of the shell session itself.
How to View All Shell Variables
At its most basic level, running the set command without any flags or arguments will dump a massive list of every single variable currently active in your shell environment.
set
Unlike the env command (which only shows exported variables), set will show you everything. This includes local shell variables, exported environment variables, and even the source code of any bash functions you have loaded into memory. Because this output is usually thousands of lines long, it is best practice to pipe it into a pager like less so you can scroll through it comfortably:
set | less
How to Change Shell Attributes (Options)
The true power of the set command lies in its ability to toggle behavioral flags (options) within the bash shell, fundamentally altering how the terminal executes your scripts.
You turn an option ON by using the minus sign (-). You turn an option OFF by using the plus sign (+). This syntax often confuses beginners, but it is a strict standard in bash.
The “Exit on Error” Option (set -e)
By default, if a bash script encounters a critical error on line 5, it will output an error message but blindly continue executing lines 6, 7, and 8. This can be disastrous if line 5 was supposed to create a directory, and line 6 is supposed to copy files into it. To force the script to abort the moment a command fails, use the -e (errexit) flag.
set -e
Placing this at the top of your script ensures the shell instantly exits if any command returns a non-zero (failure) status.
The “Debug Mode” Option (set -x)
When you have a massive script that is behaving unpredictably, it is difficult to know exactly which line is failing. You can turn on the -x (xtrace) flag to enable bash debugging.
set -x
When this is active, the terminal will print every single command to the screen before it executes it, replacing any variables with their actual calculated values. This gives you a real-time, line-by-line view of exactly what the script is doing behind the scenes. Once you have found the bug, you can turn the debugging feature back off by running set +x.