How to trap signals like SIGINT or SIGTERM in Bash?
Jul 08, 2025 am 01:20 AMThe method of using trap to capture signals is to use trap 'command' SIGNAL syntax, such as trap 'echo "Catches SIGINT, exiting..."' INT; the cleanup operation can be encapsulated into a function and binds multiple signals, such as trap cleanup INT TERM; precautions include avoiding calling complex commands such as exit in trap, setting trap multiple times will overwrite, resetting trap after child processes or exec, and debugging mode may affect behavior; actual applications include deleting temporary files, releasing resources, preventing errors in exit, and also ignoring signals such as trap '' INT; finally, test whether the trap takes effect.
In Bash scripts, system signals such as SIGINT
(Ctrl C) or SIGTERM
(termination signal) are handled, usually in order to enable the script to do some cleaning work when it is interrupted. Bash provides trap
commands to implement this, and the usage is not complicated, but some details need to be paid attention to.
How to use trap
to capture signals?
The trap
command in Bash allows you to execute a piece of code when you receive a specific signal. The basic syntax is:
trap 'command' SIGNAL
For example, if you want to output a message when the script receives SIGINT
:
trap 'echo "Catched SIGINT, exiting..."' INT
You can also write the cleaning operation into a function, which makes it clearer:
cleanup() { echo "Doing cleaning..." # Delete temporary files, close connections, etc.} trap cleanup INT TERM
This way, when the script receives INT
or TERM
signal, the cleanup
function will be called.
Common pitfalls and precautions
- Don't call complex commands in trap : the behavior of
exit
or subshells, such as exit or subshell, may lead to unpredictable results. - Multiple trap settings will be overridden : If you set traps on the same signal multiple times, only the last time will take effect.
- Remember to reset trap : If you fork a child process or execute
exec
, you may need to reset the trap. - Trap behavior may be different in debug mode : for example, under
set -x
, the output when trap is triggered may interfere with your logs.
For example, the following code is fine in most cases, but if exit
is called in the cleanup function, it may cause problems:
trap 'cleanup' INT
Examples of practical application scenarios
Delete temporary files
TMPFILE=$(mktemp) trap 'rm -f "$TMPFILE"' INT TERM EXIT
Release resources or notify other services
cleanup() { kill $BACKGROUND_PID 2>/dev/null echo "The background process has stopped" } trap cleanup INT TERM
Prevent quit by mistake
trap 'echo "Please wait, don't force exit"; exit 1' INT
These scenarios are common, especially when writing automated scripts or deploying scripts, which can effectively improve robustness.
A last tip
If you want to ignore a signal (such as not allowing the user to interrupt Ctrl C), you can do this:
trap '' INT
This is useful in some interactive scripts, but be careful, otherwise the user will feel "stuck".
Basically all that is, it's not difficult to use, but don't forget to test whether your trap is really effective.
The above is the detailed content of How to trap signals like SIGINT or SIGTERM in Bash?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

C++ is a popular programming language that is powerful and flexible and suitable for various application development. When developing applications using C++, you often need to handle various signals. This article will introduce signal processing techniques in C++ to help developers better master this aspect. 1. Basic concepts of signal processing A signal is a software interrupt used to notify an application of internal or external events. When a specific event occurs, the operating system sends a signal to the application, which the application can choose to ignore or respond to. In C++, signals can

In-depth study of audio processing and signal processing in Go language. With the development of science and technology, audio processing and signal processing technology play an important role in various fields. From music and movies in the entertainment industry to disease diagnosis and treatment in the medical field, audio processing and signal processing play a vital role. As an emerging programming language, Go language has the characteristics of high efficiency, high concurrency and simplicity of use. It is used by more and more developers for the development of audio processing and signal processing. Go language provides rich libraries for audio processing, such as

In this problem, we need to create a program that does not terminate when ctrl+C is pressed. Instead, it prints "Ctrl+C cannot terminate program." For this we can use signal processing. Pressing ctrl+c will create the signal SIGINT. To solve this problem, we will catch and handle this signal. Program showing the implementation of our solution: Example #include<stdio.h>#include<signal.h>voidsignalHandle(intsig_num){ signal(

Introduction: With the continuous development of modern science and technology, radar signal processing technology has been increasingly widely used. As one of the most popular programming languages ??at present, Java is widely used in the implementation of radar signal processing algorithms. This article will introduce the radar signal processing technology implemented in Java. 1. Introduction to radar signal processing technology Radar signal processing technology can be said to be the core and soul of the development of radar systems, and is the key technology to realize the automation and digitization of radar systems. Radar signal processing technology includes waveform processing, filtering, pulse compression, and adaptive beam shaping.

Go language is an open source programming language. It is increasingly popular among programmers because of its simplicity, ease of use, efficiency and security. In the Go language, process control and signal processing are also very important parts. This article will delve into the process control and signal processing in the Go language. Process calls in Go language Process control in Go language can realize calling and control between multiple processes. The Go language provides the os library and the exec library, which can start and call processes. By calling the command line in the os library, you can create

What are the signal processing methods in Go language? Go language is an efficient, concise programming language with native concurrency capabilities. It is widely used in network programming, distributed systems, cloud computing and other fields. In Go language, inter-process communication is implemented through pipes and signals. This article will introduce the use of signals and their processing methods in the Go language. Signals Overview A signal is a mechanism used by the operating system to send asynchronous events to processes. In Unix/Linux operating systems, signals are often used to notify processes of certain

Django is an open source Python Web framework with powerful rapid development capabilities and rich extension functions. Signal processing is one of the important features in the Django framework. It can implement custom logic in the application and enhance the flexibility and scalability of the program. This article will continue to introduce signal processing techniques in the Django framework. 1. Signal sending and receiving Signals in Django are implemented by the Signal class. Signals are sent and received through the send and con of Signal.

How to solve the problem of concurrent signal handling in Go language? Go language is an open source programming language that provides a concise and efficient programming method, which is particularly suitable for concurrent programming. In a concurrent program, signal handling is an important task. In this article, we will introduce in detail how to solve concurrent signal handling problems in Go language and provide specific code examples. First, we need to understand some basic knowledge about signal processing. In computing, a signal is a way of representing various events at the software level. common signals
