Linux_ Summary of Chapter 16 of Linux command line and shell script programming

Time:2021-10-14

Time: Tuesday, September 26, 2017
Note: some of the contents of this article are taken from the book “complete collection of Linux command line and shell script programming”, and the copyright belongs to the original author. Summary of Chapter 16 of Linux command line and shell script programming (Third Edition)

Chapter 16: control script

Contents of this chapter

Signal processing
Run script in background mode
Prohibit pending
Job control
Modify script priority
Script execution automation

16.1 signal processing

16.1.1 rewind Linux signal

Linux system signal

Linux uses signals to communicate with processes running in the system
Signals can be used to stop / start / terminate processes
You can control the shell script by programming the script to execute certain commands when it receives a specific signal
By default, the bash shell ignores any 3 and 15 signals it receives
But the bash shell handles the 1 and 2 signals

Common Linux system signals

Signals: values: description
1: SIGHUP: suspend process
2: SIGINT: terminate process
3: Sigquit: stop the process
9: Sigkill: unconditionally terminate the process
15: SIGTERM: terminate the process as much as possible
17: Sigstop: unconditionally stop the process, but not terminate the process
18: Sigtstp: stops or pauses a process without terminating it
19: Sigcont: continue running the stopped process

16.1.2 generating signals

1. Interrupt the process

Using Ctrl + C generates a 2 (SIGINT) signal and sends it to all processes currently running in the shell

Execute command

sleep 100
^C

Note: ^ refers to Ctrl key

2. Suspension of the process

Using Ctrl + Z generates an 18 (sigtstp) signal to stop any process running in the shell

Execute command

sleep 100
^Z

When pressing Ctrl + Z, the bash shell will give the following prompt

[1]+  Stopped sleep 100
The number in square brackets is the job number assigned by the shell
The shell calls each process running in the shell a job and assigns a unique job number to each job
If there are stopped jobs in the shell reply, bash will remind you when you exit the shell

Common operation

ps -l
View the stopped jobs, and show t as the stopped jobs in the s column (process status)
kill -9 PID
Terminate the job with the specified PID, and terminate the PID of the stopped job
Generally speaking, it is to kill the process

16.1.3 acquisition signal

Command format: trap commands signals
Command description: use the trap command to specify the Linux signals that the shell script should monitor and intercept from the shell

Use the trap command to ignore the SIGINT signal

Write test1.sh script

#!/bin/bash

trap "echo 'Sorry!I have trappend Ctrl-C'" SIGINT

echo This is a test script

count=1
while [ $count -le 10 ]
do
    echo "Loop #$count"
    sleep 1
    count=$[ $count+1 ]
done

echo "This is the end of the test script"

16.1.4 capture script exit

Capture exit signal of shell script

Write test2.sh script

#!/bin/bash

trap "echo Goodbye..." EXIT

count=1
while [ $count -le 5 ]
do
    echo "Loop #$count"
    sleep 1
    count=$[ $count+1 ]
done

16.1.5 modify or remove capture

After modifying the signal capture, the script will still process according to the original trap command

Write test3.sh script

#!/bin/bash
#
trap "echo 'Sorry.. Ctrl+C is trapped.'" SIGINT
#
count=1
while [ $count -le 5 ]
do
    echo "Loop #$count" 
    sleep 1
    count=$[ $count+1 ]
done
#
trap "echo 'I modified the trap!'" SIGINT
#
count=1
while [ $count -le 5 ]
do
    echo "Loop #$count" 
    sleep 1
    count=$[ $count+1 ]
done

Add two dashes between the trap and the signal list to delete the set capture and restore the default behavior

Write test3b.sh script

#!/bin/bash
#
trap "echo 'Sorry.. Ctrl+C is trapped.'" SIGINT
#
count=1
while [ $count -le 5 ]
do
    echo "Loop #$count" 
    sleep 1
    count=$[ $count+1 ]
done
#
# Remove the trap
trap -- SIGINT
echo "I just removed the trap"
#
count=1
while [ $count -le 5 ]
do
    echo "Loop #$count" 
    sleep 1
    count=$[ $count+1 ]
done

Knock: you can also use a single dash after the trap command to restore the default behavior of the signal. Both single and double dashes work properly

16.2 running script in background mode

16.2.1 background running script

Run the shell script in background mode with an & sign after the command

Write test4.sh script

#!/bin/bash
count=1
while [ $count -le 10 ]
do
    sleep 1
    count=$[ $count+1 ]
done

Execute command

./test4.sh &

Then [1] 3231 is displayed
The number in square brackets indicates the job number of the background process, and the following number is the process ID (PID) of the process

When the daemon is running, it still uses the terminal display to display stdout and stderr messages

Write test5.sh script

#!/bin/bash
#
echo "Start the test script"
count=1
while [ $count -le 5 ]
do
    echo "Loop #$count"
    sleep 5
    count=$[ $count+1 ]
done
#
echo "Test script is complete"

When the script is running in the background mode, the output of the script is mixed with the input command and command output. It is best to redirect stdout and stderr of the script running in the background to avoid messy output

16.2.2 running multiple background jobs

You can use the & symbol to start multiple background jobs at the command prompt at the same time
Use the PS command to view the running status of all scripts
Be careful when using the background process in the terminal session. When you exit the terminal, the background process will also exit

16.2.3 running scripts under non console

Command format: nohup. / test1.sh&
Command description: use the nohup command to start the shell script in the terminal session and let the script run in background mode until the end. Even if you exit the terminal session, the shell script will run all the time

Execute command

nohup ./test1.sh &
cat nohup.out

explain

When using nohup to start the shell script, the script will ignore the SIGHUP signal sent by the terminal session
Since the nohup command will disassociate the terminal from the process, the process is no longer associated with stdout and stderr
The nohup command will automatically redirect stdout and stderr messages to a file named nohup.out in the current directory
If you run another script using the nohup command, the output of the script is appended to the existing nohup.out file

16.4 operation control

These functions of starting / stopping / terminating and resuming jobs are collectively referred to as job control

16.4.1 viewing jobs

Use the jobs command to view the job currently being processed by the shell. The script $$variable displays the PID assigned to the script by the Linux system

Write test10.sh script

#!/bin/bash
#
echo "Script Process ID: $$"
#
count=1
while [ $count -le 10 ]
do
    echo "Loop #$count"
    sleep 10
    count=$[ $count + 1 ]
done
#
echo "End of script..."
#

Execute command

./test10.sh > test10.out &
View job
jobs
View job的PID
jobs -l

Jobs command parameters

Parameters: description
-l: List the PID and job number of the process
-n: Only jobs whose status has changed since the last notification from the shell are listed
-p: Only the PID of the job is listed
-r: List only running jobs
-s: List only stopped jobs

Plus and minus signs in jobs command output

Jobs with a plus sign are treated as default jobs
When using the job control command, if no job number is specified on the command line,
    The job will be treated as the operation object of the job control command
After the current default job is processed, the job with minus sign becomes the next default job
There is only one job with a plus sign and one job with a minus sign at any time,
    No matter how many jobs are running in the shell

16.4.2 restart the stopped operation

Command format: BG job number
Command description: restart the specified job in background mode
Command format: FG job number
Command description: restart the specified job in foreground mode

16.5 adjust humility

In a multitasking operating system (Linux is), the kernel is responsible for allocating CPU time to each process running on the system
Scheduling priority is the CPU time allocated by the kernel to a process (relative to other processes)
In Linux system, the scheduling priority of all processes started by shell is the same by default
Scheduling priority is an integer value from - 20 (highest priority) to + 19 (lowest priority)
By default, the bash shell starts all processes with priority 0

Knock on the door: the lowest value of – 20 is the highest priority, and the highest value of 19 is the lowest priority, which is too easy to remember. Just remember the saying “a good man is hard to do”. The better or higher the value, the lower the chance of obtaining CPU time

16.5.1 nice command

Use the nice command – n parameter to specify a new priority level

Execute command

nice -n 10 ./test4.sh > test4.out &
View job information
ps -p 3678 -o pid,ppid,ni,cmd
nice -10 ./test4.sh > test4.out &
ps -p 3706 -o pid,ppid,ni,cmd

16.5.2 renice command

Use the renice command to specify the priority of running the process PID

Execute command

./test4.sh &
ps -p 3742 -o pid,ppid,ni,cmd
renice -n 10 -p 3742
ps -p 3742 -o pid,ppid,ni,cmd

Some limitations of the renice command

Renice can only be performed on processes that belong to you
You can only lower the priority of a process through renice
The root user can arbitrarily adjust the priority of the process through renice

16.6 regular operation

16.6.1 use the at command to plan and execute the job

1. Format of at command

Command format: at [- f filename] time
Command description: use the – f parameter to specify the file name of the script file to be executed, and the time parameter determines when to run

Many different time formats

Standard hour and minute formats, such as 10:15
AP / PM indicator, e.g. 10:15pm
Specific named times, such as now, noon, midnight, or teatime (4pm)
Standard date formats, such as mmddyy, mm / DD / YY, or dd.mm.yy
Text date, such as junl4 or dec25, with or without year
You can also specify time increments
    Current time + 25min
    Tomorrow 10:15pm
    10: 15 + 7 days

2. Get job output

When running on a Linux system, the display is not associated with the job. The Linux system will send the output of stdout or stderr to the user through the mail system

Write test13.sh script

#!/bin/bash
echo "This script ran at $(date +%B%d,%T)"
echo
sleep 5
echo "This is the script end..."

Execute command

at -f test13.sh now

Use the – M option to mask the output information generated by the job

Write test13b.sh

#!/bin/bash
echo "This script ran at $(date +%B%d,%T)" > test13b.out
echo >> test13b.out
sleep 5
echo "This is the script end..." >> test13b.out

Execute command

at -M -f test13b.sh now
cat test13b.out

3. List the waiting jobs

The atq command checks which jobs are waiting in the system and displays the job list
The job number is displayed in the job list, and the date and time when the system runs the job and its job queue

4. Delete job

Command format: ATRM job number
Command description: use ATRM to delete the specified job

16.6.2 schedule scripts that need to be executed regularly

1. Cron schedule

Command format: Min hour dayofmonth month DayOfWeek command
Command description: cron schedule uses a special format to specify when jobs run

Format description

DayOfWeek: text (Mon, Tue, wed, thu, Fri, sat, sun) or numeric value (0 is Sunday, 6 is Saturday)
Dayofmonth: indicates the date value in the month (1 ~ 31)

Cron instance

Run a command at 10:15 every day
15 10 * * * command
Commands run at 4:15PM every Monday
15 16 * * 1 command
Execute the order at 12 noon on the first day of each month
00 12 1 * * command
Execute the command on the last day of each month
00 12 * * * if [‘date +%d -d tomorrow’ = 01]; then;command
Note: check whether it is the last day of the month at 12 noon every day. If so, cron will run the command

Execute command

15 10 * * * /home/zc/test/unit16/test4.sh > test4.out

2. Build cron schedule

Linux provides crontab to handle cron schedules, and uses cron schedules to run scheduled tasks

Command format: crontab – L
Command description: use crontab – L to list existing cron schedules

3. Browse cron directory

If the script you create does not require high precision execution time, you can use the preconfigured cron script directory

Four basic directories

Hourly: executed every hour
Daily: executed every day
Monthly: monthly
Weekly: Weekly

Execute command

ls /etc/cron.*ly

4. Anacron program

Cron program can only ensure that the Linux system can execute scheduled tasks when it is turned on. When the Linux system is turned off, it will not execute scheduled tasks

Using anacron program, when the Linux system is powered off, it knows that a job has missed the execution time. When the Linux system is powered on, it will run the job as soon as possible

The anacron program only handles programs located in the cron directory, such as / etc / cron.monthly

Command format: period delay identifier command
Command description: period defines how often the job runs, in days.

Note: the anacron program will not process scripts whose execution time is less than one day, such as those located in / etc / cron.hourly

16.6.3 start script with new shell

Every time you start a new shell, the bash shell runs the $home /. Bashrc file

verification

Add echo "I'm in a new shell" at the end of the $home /. Bashrc file
Then save and close the shell terminal
When you reopen the shell terminal, you can see the prompt

16.7 summary

This chapter mainly explains the signal control in Linux, executing scripts in background mode, executing scripts at a specified time, modifying the priority of scripts, etc.