Get the App
SLTechnology News&Howtos  ›  Servers  › 

What are the details of Linux Shell's signal trap function?

Shulou Source: shulou.com Published: 2022-06-01 03:23:59 09月19日 Update

This article introduces what are the details of the signal trap function of Linux Shell, the content is very detailed, interested friends can refer to, hope to be helpful to you.

It has three forms corresponding to three different ways of signal response.

First: trap 'commands' signal-list when the script receives the signal listed in the signal-list list, the trap command executes the command in double quotes.

The second: trap signal-list trap does not specify any commands and accepts the default operation of the signal. The default action is to end the running of the process.

Third: the trap''signal-list trap command specifies an empty command string that allows you to ignore the signal.

NOTE:trap can only set one setting for the same signal. If you set multiple trap in a shell, it will only respond to the last signal setting.

Such as: trap 'echo "aaaaaaaaaaa" INT

Trap 'echo "bbbbbbbbbbb"' INT

Then it will only respond to the last signal setting.

Some of the more important signals that can be captured as specified in the following X/Open specification (the numbers in parentheses are traditional signal numbers)

A common use of the trap command is to clean up when the script is interrupted, such as temporary files.

An example of trap command

Eg 1:

[root@xyhl ~] # trap "echo aaaaaa" 2

[root@xyhl ~] # ^ Caaaaaa = = "execute ctrl+c, capture signal 2, and print

Eg 2: if you encounter an INT interrupt, that is, Ctrl+c, delete the file

#! / bin/bash

Trap'rm-f / tmp/my_tmp_file_$$' INT

Echo "creating file / tmp/my_tmp_file_$$"

Date > / tmp/my_tmp_file_$$

Echo "press interrupt (CTRL-C) to interrupt."

While [- f / tmp/my_tmp_file_$$]

Do echo "File exists"

Sleep 3

Done

Echo "we never get here" exit 0

About the Linux Shell signal trap function details are shared here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Tags: Signals commands functions details content files more scripts help different good important three forms tradition interest multiple guys buddies common quotation marks Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL OPPO Reno Docker Microsoft NVidia