set -x
The set -x command in a Bash script enables a mode of the shell where all executed commands are printed to the terminal. This action can be extremely valuable during script debugging, as it grants the ability to see each command as it's processed. This feature is often referred to as xtrace.
set -x prints each command that is executed in the shell script to the console or terminal. It's a useful way to track the execution flow of a bash script, especially when we are debugging.
For instance, let's take a look at the following script:
#!/bin/bash
set -x
echo "This is a sample program"When this script runs, the output will look like:
+ echo 'This is a sample program'
This is a sample programLet’s see another example.
#!/bin/bash
set -x # Enables xtrace
echo "This will be printed with a trace."
set +x # Disables xtrace
echo "This won't be printed with a trace."Running this script would produce:
This demonstration shows every line executed from the point set -x is called until the command set +x is called. After set +x the normal operation resumes, i.e. commands will not be printed before their execution.
set -e
set -e in a Bash script is used to instruct the shell to exit immediately if any command it executes fails, i.e., if it returns a non-zero exit status.
In shell scripting, normally, even if a command fails (exits with a non-zero status), the script will continue to execute the remaining commands. When we set the -e option (also known as 'errexit'), we change this default behavior.
For example, let’s consider this simple script without set -e:
#!/bin/bash
cd /non-existent-dir
echo "This is a sample program"Even though the cd command will fail, the echo command will still get executed giving the below output.
./myscript.sh: line 2: cd: /non-existent-dir: No such file or directory
This is a sample programHowever, if we put set -e, at the start of the script:
#!/bin/bash
set -e
cd /non-existent-dir
echo "This is a sample program"The echo command will never be reached. The script will abort after the cd command fails to change to a non-existent directory.
In conclusion, set -e is a useful method to make sure every command we run is successful and to get scripts to stop as soon as something unexpected.




