set -x set -e set -u

Key words

set -x
set -e
set -u
shell脚本调试

How to better debug shell scripts

The easiest way is to use -xparameters, this is more familiar than everyone, the usage is as follows

bash -x myscript.sh

If our script is very long, and we only need to debug a small section in the middle, so that debugging the entire script, the output content is too much, at this time we can set -xturn on the detailed output inside the script , and then set +xcancel the detailed output in the appropriate place

$ cat hello.sh
echo hhs 
pwd
i=666
set -x
echo $i
set +x
[dc2-user@10-255-20-218 ~]$ bash hello.sh
hhs
/home/dc2-user
+ echo 666
666
+ set +x

How to control script errors more accurately

We know that for shell scripts, an empty variable will not report an error, and this may cause problems in some cases. For example, we use grep with awk to get a value. Under normal circumstances, we know that we can get a value. At this time We can add set -uthis line at the beginning of the script, which means that once the entire script encounters an undefined variable, for example, if we do not get the value with the command, we will directly report an error and exit without continuing to execute

There is another situation. For example, if we add such a command to the shell script, an cat /etc/redhat-releasexxxerror will be reported when executing this command, but the shell script will continue to execute. If this is not what we want, we can add this at the beginning of the shell script.set -e

Summarized as follows:

  • set -u #When encountering undefined variables, exit immediately
  • set -e #If the command execution fails (returns non-zero), exit immediately

Full usage of the set command

help set

Guess you like

Origin blog.csdn.net/xys2015/article/details/114105019
set
set