Coder Perfect

What does `set -x` do?


I have a shell script with the following line in it:

[ "$DEBUG" == 'true' ] && set -x

Asked by Ole

Solution #1

set -x switches the shell to a mode where all commands are printed to the terminal. It’s evident that you’re using it for debugging, which is a common use case for set -x: showing every command as it’s executed might help you visualize the script’s control flow if it’s not working as anticipated.

set +x turns it off.

Answered by John Zwinck

Solution #2


set -x
echo `expr 10 + 20 `
+ expr 10 + 20
+ echo 30
set +x
echo `expr 10 + 20 `

The use of set -x is seen in the above example. The above mathematical expression has been expanded when it is employed. We were able to examine how a single line was evaluated one step at a time.

Visit this link to learn more about the set.

When it comes to your shell script, make sure it’s as simple as possible.

[ "$DEBUG" == 'true' ] && set -x

When the execution mode was set to DEBUG, your script may have printed some extra lines of information. When a script was called with an optional argument such as -d, people used to enable debug mode.

Answered by Raju

Solution #3

Consider the following distinctions:

/ # set -v && echo $HOME
/ # set +v && echo $HOME
set +v && echo $HOME

/ # set -x && echo $HOME
+ echo /root
/ # set +x && echo $HOME
+ set +x

/ # set -u && echo $NOSET
/bin/sh: NOSET: parameter not set
/ # set +u && echo $NOSET

Answered by lupguo

Solution #4

Instead of using set -x and set +x, we can use -x to run the script. ksh -x script name is one example. ksh If I’m mistaken, please correct me or expand my understanding.

Answered by Faisal

Post is based on