Consider following script example:
$ cat > testsign |
Save and run it as
$ chmod +x testsign
$ ./testsign
Now if you press ctrl + c , while running this script, script get terminated. The ctrl + c(ctrl + c: stop; ctrl + d: save) here work as signal, When such signal occurs its send to all process currently running in your system. Now consider following shell script:
$ cat > testsign1 |
Save it and run as
$ chmod +x testsign1
$ ./testsign1
It first ask you main database file where all appointment of the day is stored, if no such database file found, file is created, after that it open one temporary file in /tmp directory, and puts today's date in
that file. Then one infinite loop begins, which ask appointment title, time and remark, if this information is correct its written to temporary file, After that, script asks user , whether he/she wants to add next appointment record, if yes then next record
is added , otherwise all records are copied from temporary file to database file and then loop will be terminated. You can view your database file by using cat command. Now problem is that while running this script, if you press CTRL + C, your shell script
gets terminated and temporary file are left in /tmp directory. For e.g. try it as follows
$./testsign1
After given database file name and after adding at least one appointment record to temporary file press CTRL+C, Our script get terminated, and it left temporary file in /tmp directory, you can check this by giving command as follows
$ ls /tmp/input*
Our script needs to detect such signal (event) when occurs; To achieve this we have to first detect Signal using trap command.
Syntax:
trap {commands} {signal number list}
| Signal Number | When occurs |
| 0 | shell exit |
| 1 | hangup |
| 2 | interrupt (CTRL+C) |
| 3 | quit |
| 9 | kill (cannot be caught) |
To catch signal in above script, put trap statement before calling Take_input1 function as trap del_file 2 ., Here trap command called del_file() when 2 number interrupt ( i.e. CTRL+C ) occurs. Open above script in editor and modify it so that at the end it will look like as follows:
|
|
Run the script as:
$ ./testsign1
After giving database file name and after giving appointment title press CTRL+C, Here we have already captured this CTRL + C signal (interrupt), so first our function del_file() is called, in which it gives message
as "* * * CTRL + C Trap Occurs (removing temporary file)* * * " and then it remove our temporary file and then exit with exit status 1. Now check /tmp directory as follows
$ ls /tmp/input*
Now Shell will report no such temporary file exit.
本文详细介绍了如何在Shell脚本中使用trap命令捕获并处理中断信号(如Ctrl+C),确保在用户中断脚本执行时能够清理临时文件并保持脚本的正常运行流程。通过修改脚本以实现信号处理,用户可以避免意外终止脚本导致的数据丢失问题。
1391

被折叠的 条评论
为什么被折叠?



