LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   How do i run a part of code on exit in a shell script? (http://www.linuxquestions.org/questions/programming-9/how-do-i-run-a-part-of-code-on-exit-in-a-shell-script-807784/)

saiteju 05-14-2010 05:09 AM

How do i run a part of code on exit in a shell script?
 
How do i run a part of code on exit in a shell script?

Suppose i have four echo statements like the following:

echo "Stmt 1"
echo "Stmt 2"
....some code goes here...

echo "Stmt 3"
echo "Stmt 4"

Suppose the first 2 echo statements are executed and then the user exits the script manually...is there a way to print the last two echo statements when the user exits the script manually?

catkin 05-14-2010 05:17 AM

Depends what you mean by "when the user exits the script manually". If it's by interaction with the script then it is under script control and you can program whatever you like. If it is by Ctrl+C then you can use bash' trap command to configure what is done on receipt of the signal. There are other ways of terminating a script: shutdown, logoff (if script is running in the background), sending a signal to it (for example by the kill command) ....

If the script is becoming so sophisticated it may be most convenient to write a single function which is called when the script terminates for whatever (interceptable) reason.

colucix 05-14-2010 05:22 AM

It depends on the method used to exit manually. If the user can terminate the script using Ctrl-C, you can trap the signal sent to the script and execute whatever you want. The same if the EXIT signal (not interruption) is sent to the script. See these two examples on the Advanced Bash User Guide to get the idea.

Edit: Beaten by catkin... ;)


All times are GMT -5. The time now is 08:07 PM.