Use the Bash trap Statement to Clean Up Temporary Files
The trap statement in bash causes your script to execute one or more commands when a signal is received. One of the useful things you can use this for is to clean up temporary files when your script exits.
To execute code when your script receives a signal, use the following syntax:
trap arg sigspec...
The "arg" is the command to execute. If the command contains spaces, quote it. You can include multiple commands by separating them with semicolons. For more complex things, put your exit code in a function and just invoke the function. The "sigspec" list is a list of signals to trap and then execute "arg" (if/when they occur). For example, to remove a file on EXIT, do the following:
trap "rm -f afile" EXIT
Note that EXIT is not a real signal (do kill -l to see all signals); it is synthesized by bash.
Be careful using wildcards in "arg", because if they are unquoted or quoted with double quotes, they get expanded when the trap statement is encountered and not when "arg" is executed. For example, if you have a file named "abc.tmp" and the following trap statement is executed:
trap "rm -f *.tmp" EXIT
the command that gets executed when the script exits is "rm -f abc.tmp" and not "rm -f *.tmp". To avoid this problem, use single quotes.
If you create temporary files at various places in your code and you don't use a naming convention that would allow you to use a wild card in your trap statement and you don't want to worry about changing your trap statement as your code evolves, you could write something like this to allow you to add new trap commands that get executed on exit:
#!/bin/bash
declare -a on_exit_items
function on_exit()
{
for i in "${on_exit_items[@]}"
do
echo "on_exit: $i"
eval $i
done
}
function add_on_exit()
{
local n=${#on_exit_items[*]}
on_exit_items[$n]="$*"
if [[ $n -eq 0 ]]; then
echo "Setting trap"
trap on_exit EXIT
fi
}
touch $$-1.tmp
add_on_exit rm -f $$-1.tmp
touch $$-2.tmp
add_on_exit rm -f $$-2.tmp
ls -la
Here the function add_on_exit() adds commands to an array, and the on_exit() function loops through the commands in the array and executes them on exit. The on_exit function gets set as the trap command the first time add_on_exit is called.
Mitch Frazier is an Associate Editor for Linux Journal and the Web Editor for linuxjournal.com.










This week 5 lucky Members will receive a copy of The Official Ubuntu Server Book by Benjamin Mako Hill and Linux Journal's very own Kyle Rankin. No entry necessary. Check back here early next week to find out who the lucky Online Members are.




Comments
Bugs in the article's scripts?
First, a caveat: I rarely use Bourne-shell scripts. Still, I was unable to get
the example cited in the article running, and I believe that is caused by at least
two problems in the illustrative example scripts.
It seems to me that the exit commands have to be quoted when add_on_exit
is invoked; i.e., add_on_exit "rm -f $$-1.tmp" instead of add_on_exit rm -f $$-1.tmp ,
no? Also, shouldn't the command be assigned to a new element of the on_exit_items
array using on_exit_items="([$n]=$*)" ?
isohedral
Works for me
The example script works for me.
The exit commands could be quoted when calling add_on_exit but they don't have to be. The entire command line (to add_on_exit) is quoted when it is added to the array:
on_exit_items[$n]="$*"and the commands are added to a new element of the array:
local n=${#on_exit_items[*]} on_exit_items[$n]="$*"The syntax that you suggest for appending to the array does not preserve the existing elements.
Mitch Frazier is an Associate Editor for Linux Journal and the Web Editor for linuxjournal.com.
bash script to capture stdin
Hi there, firstly, excellent article!
I am running a script on my ubuntu system to pair my BT mouse with my laptop. I'd like at one to point capture keyboard input to proceed with the pairing. I am running the script graphically by double-clicking the executable, and I do NOT wish to open a terminal.
Is there a way to do this using TRAP? Either to tell the script to wait for a keyboard signal, or maybe call some other program that does so?
Details can be found here:
http://www.linuxforums.org/forum/linux-programming-scripting/150535-absolute-begginer-needs-help-some-scripting-issues.html#post716361
-Thanks!
Keyboard
There's not a "keyboard" trap that you can catch and beyond that since you haven't opened a terminal you don't even have a keyboard "connected" to your script. This is actually an important point: when you run a shell script from a GUI launcher, things aren't as you perhaps expect them to be. If you run ls -la /proc/$$/fd from a terminal window you'll see something like:
showing your stdin/stdout/stderr connected to the terminal.
If however you were to run that same command from a script launced by a GUI launcher you would see something like this:
So all output ends up in your ~/.xsession-errors file and your input (stdin) is not even connected to anything useful. Note that when I said see above, I meant you'd see it in your ~/.xsession-errors file.
That said, seems to me there's a simple solution to this problem: since you don't want to open a terminal why don't you use zenity or something to ask the question in a GUI dialog box, eg:
if zenity --timeout 2 --question --text 'Connect BT mouse? '; then # connect mouse ...or:
zenity --timeout 2 --question --text 'Connect BT mouse? ' if [ $? -eq 0 ]; then # connect mouse ...Mitch Frazier is an Associate Editor for Linux Journal and the Web Editor for linuxjournal.com.
Worked like a charm and had
Worked like a charm and had the added side-effect of making my pairing process more robust. I'm not sure why, but for some reason, I no longer need to physically put the mouse in pairing mode (a real blessing) by pressing connect on the mouse!
Thank you!
Thanks kindly! Sorry for the
Thanks kindly!
Sorry for the delay, I had not noticed how swiftly you'd replied!
I think your solution solves the problem, and I do understand the problem better now. If you don't mind, I am linking to here and marking the forum threads closed.
Thansk again!
some excellent references to clarify things a bit
http://www.linuxjournal.com/content/bash-arrays
http://www.linuxjournal.com/content/bash-parameter-expansion
thanks A LOT!
was very useful! thanks a lot for that article.
Works Similarly On Korn Shell, Too
This also works in ksh (Korn Shell), with one exception: the "declare" keyword has to be replaced with "typeset" (ie. "typeset -a on_exit_items").
Post new comment