bash scripting … switching into directory of the script

Sometimes it is useful to switch into the directory of the script e.g. when we need to call or include further files and don’t want to go through the hassle of searching for the script in the file system. Especially when symlinks are involved everything get a bit more interesting. This little snippet switches into the directory of the script, using readlink to dereference symlinks if the script is called via a symlink.

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.