Linux Shell Scripting Tutorial (LSST) v1.05r3 | ||
Chapter 4: Advanced Shell Scripting Commands | ||
|
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 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.
| ||
User Interface using dialog Utility - Putting it all together | The shift command |