Shell script is used to monitor the execution process of shell script and the value of variables


Many times, we will write shell programs to complete some moments without repeated wheel building. However, because there will be functions and variables in the shell statements, we need to monitor the variables and other variable factors in the specific execution process because of which related operations are executed after running. Let’s write a small shell example below, To monitor the changes of variables in conditional statements during execution and observe the execution process of the whole program.

Shell program code:

Copy codeThe code is as follows:
function setlogfile
    if ! [ -z “$1” ]; then
        echo “logfilename is not empty!” >> kthh
        exec 2>> $1
        exec 1>> $1


setlogfile ${execlogfile}
set -x
if [ $num1 -eq 0 ]; then
    echo “num1 is 0”>> ${logfile}
elif [ $num1 -ge 0 ]; then
    echo “num1 is grate 0”>> ${logfile}
    echo “num1 is less 0”>> ${logfile}
/sbin/shutdown -k 10
if [ $num1 -eq 0 ]; then
    echo “num1 is 0 again”>> ${logfile}

Execute on the command line:

Copy codeThe code is as follows:
[[email protected] shellprogram]# ./ 0 msglog execlog

In the above shell script, the value corresponding to num1 is 0 in the command line, the value of # logfile is msglog, and the value of # execlogfile is execlog.

The setlogfile function uses the setlogfile log file name. In the example, use setlogfile ${execlogfile}, and exec 2 > > $1 in the function; Exec 1 > > $1 means redirecting the information of standard output and standard error output to the execlog file.

Now let’s take a look at the contents of execlogfile, and we can see the execution process of shell program and the change of variable value in the execution process.

Copy codeThe code is as follows:
[[email protected] shellprogram]# cat execlog
+ ‘[‘ 0 -eq 0 ‘]’
+ echo ‘num1 is 0’
+ /sbin/shutdown -k 10
+ ‘[‘ 0 -eq 0 ‘]’
+ echo ‘num1 is 0 again’

It can be seen that the process in the program is and/ testexecutelog. Determined by the first parameter after sh. You can also change the first parameter to a value greater than or less than 0 for testing.

The most important sentence is set – x, which means: after each simple command is extended, the PS4 extension value is displayed, followed by the command to be executed. If this sentence is not executed, the actual value of the variable in execution will not be printed to execlog. You can learn more about the use of set.

Note: when exec operates on the file descriptor, only at this time, exec will not overwrite your current shell environment. That is, a new process will not be started.