General Practice
Cat>test.SH<<eof"'#!/bin/Bashexit_script () {Exit1}Echo "before Exit"Exit_scriptEcho "After exit"EOFchmodA+x test.SH./test.SHEcho$?# output before exit1
You can see that direct use exit
can exit the script, and you can pass the error code as an argument. Let's make a little change to the script.
Problems that exist
Cat>test.SH<<eof"'#!/bin/Bashexit_script () {Exit1}Echo "before Exit":|Exit_scriptEcho "After exit"EOFchmodA+x test.SH./test.SHEcho$?# Output before Exitafter exit0
管道(|)
executing a exit_script
function in, does not exit the entire script! The reason is that you exit
can only exit it Shell
, and the 管道
command/function that is executed in is executed in isolation Shell(Sub-Shell)
, so the process tree of the above script looks like this:
PPID PID pgid SID TTY tpgid STAT UID time COMMAND17510269592695926959 pts/014049 Ss00:XX \_-bash26959138431384326959 pts/0 14049 S 0 0:00 | \_/bin/bash./test.sh138431384413843 26959 pts/0 14049 S 0 0:xx | | \_:13843 13845 13843 26959 PTS
/0 14049 S 0 0:00 | | \_/bin
/bash./test.sh13845 13846 13843 26959 pts/0 14049 S 0 0:00 | | \ _ Exit 1
From the top down, the meanings of each PID are shown in the following table:
pid |
< Span style= "FONT-SIZE:16PX;" > description |
26959 |
. The shell where/test.sh resides |
13843 |
In the pipeline: the newly opened shell |
13844 |
: command |
13845 |
Exit_shell newly opened Shell in the pipeline |
13846 |
Exit command |
Use
trap
And
kill
Exit the entire script
Cat>test.SH<<eof"'#!/bin/Bashexport top_pid=$ $trap'Exit 1'Termexit_script () {Kill-s term $TOP _pid}Echo "before Exit":|Exit_scriptEcho "After exit"EOFchmodA+x test.SH./test.SHEcho$?# output before exit1
Here is the first signal in the main process of the script 捕获(trap)
TERM
: When the main process receives the TERM
signal, it executes, and exit 1
then sends a signal to the Sub-Shell
script master process TERM
, so that the entire script can be exited!
Shell, exit the entire script