Shell programming trap

Source: Internet
Author: User

Trap allows you to capture signals in the script. The common form of this command is:

Trap name signal (s)

Among them, name is a sequence of operations taken after the captured signal. In real life, name is generally a function specifically used to process the captured signal. Name must be enclosed in double quotation marks. signal is the signal to be captured.

The script usually takes some action after capturing a signal. The most common actions include:

1) Clear temporary files

2) Ignore this signal

3) Ask the user whether to terminate the script.

Common signals include 1, 2, 3, and 15.

1----sighup suspended or the parent process is killed

2----sigint: keyboard interrupt <Ctrl + C>

3----sigquit: Exit from the keyboard

15----sigterm soft termination

Instance: trap. Sh

#! /Bin/sh
Trap "my_exit" 1 2 3 15

Loop = 0
Hold1 =/tmp/hold1. $
Hold2 =/tmp/hold2. $
My_exit ()
{
Echo-e "\ nreceived interrupt ..."
Echo "do you wish to really exit ?? "
Echo "Y: Yes"
Echo "N: No"
Echo-n "your choice [y .. n]>"
Read ans
Case $ ans in
Y | Y) Exit 1 ;;
N | N );;
Esac
}
Echo-n "enter your name :"
Read name
Echo-n "Enter your age :"
Read age

After the script captures the signal 2, it will provide you with a choice to ask whether the user really wants to exit.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.