Bash scripting, traps and sleep

Today I ran into any old problem: you have a script that should do something when it recieves a signal (e.g. if someone sends it USR1 it should write to a log/syslog), but the script uses a long sleep because it normally only checks/calculates stuff every x min. If you send it a kill -USR1 $pid it will normally execute the trap AFTER the sleep is done, not so great. I figured of the following solution today: put the sleep in a while loop that checks if the full time was slept, and inside the loop a sleep that sleeps the X seconds remaing in the background followed by a wait.

If the script now recieves a USR1 it can kill the wait, execute the trap and will continue the remaining sleep on the next iteration of the loop.

Reboot Script for Linksys WAP200 access points

Since the Linksys WAP200 has a tendency to hang and not let any users connect anymore, this little script to reboot an accesspoint (webinterface still works fine). Replace user and password with correct values.

bash foo

Instead of writing tons and tons of small scripts < 10 lines that all depend on each other I have the habbit of writing them as functions and throwing them into one file (easier to edit, less worries about them depending on each other). To be able to use the functions from the bash shell, just add $(basename $0) “$@” to the END of the file, and add symlinks function_name -> file.

Example:
$ ln -s foo.sh foobar

$ cat foo.sh


rrdtool tricks / tips

There are various different ways to generate rrdtool images. And most people will probably be generating elaborate ones out of perl or php scripts. The ones I am currently generating are built in a shell script (bash) and I was really having a problem with quotes and white space here for a while. If you generate the query and save it in a variable, the quotes go to hell and your white space (e.g. a space in a COMMENT) starts causing problems. my solution may not be the best, but it works without any trouble: Throw the whole command line into a temporary file and then use eval to create the graph. The following is not a complete statement, just a few lines as an example.

self0wned

Doh, I was just writing a bash script to calculate the current network traffic and write it to syslog. nothing special. I’m posting this from my laptop because I was forced to reboot my main PC after accidently writing a fork bomb. I wanted to recursively call myself and detatch the process so I could use the script as a deamon without worring about it if I logout.

AFTER starting the script, I noticed a flaw in my “if” startement to make sure I don’t DOS myself. By the time I got around to “hmm, maybe I should check the pid of that child and kill it so it doesn’t go and suck up my resources” it was too late. duh.