Small scripts for repetitive tasks
One thing that I like to do is write a script for seemingly trivial things that I do more than once. I do this as it turns out that I end up needing them again.
One example is a pair of script I use when testing rst2pdf. rst2pdf’s tests work by creating a PDF and then comparing this to a reference PDF. If they are different, then the test has failed. When a test fails, I need open up the PDF created by the test that’s in tests/output/{test-name}.pdf and also the reference pdf in tests/reference/{test-name}.pdf. This isn’t difficult, it’s just this command line:
$ open "tests/output/test-name.pdf" && open "tests/reference/test-name.pdf"
I use the && operator as sometimes a test fails and doesn’t create a PDF. I usually don’t immediately notice this and do not need to see the reference PDF when this situation occurs.
Not difficult to write and history makes it easy enough to find a previous command and edit appropriately.
However, it’s tedious enough to edit a command line, that I just wrote a script:
~/bin/openpdfs:
#!/usr/bin/env bash
# open the rst2pdf test result PDF and the reference one
open "tests/output/$1" && open "tests/reference/$1"
Took 5 minutes and I made working on rst2pdf that much easier as I can now just do:
$ openpdfs test-name.pdf
While using it, I soon discovered that when copying the name of the failed test, I sometimes didn’t copy the .pdf extension when double clicking, so I tweaked:
#!/usr/bin/env bash
# open the rst2pdf test result PDF and the reference one
basename=$(basename "$1")
name=$(echo "$basename" | cut -f 1 -d '.')
open "tests/output/$name.pdf" && open "tests/reference/$name.pdf"
This little addition meant that I could be more lax with the copy from the command line output, which again makes working with the script that much easier and more pleasant.
I also noticed that sometimes I’d fail to paste and would run openpdfs without any argument, so I added some help info:
#!/usr/bin/env bash
# open the rst2pdf test result PDF and the reference one
if [ -z "$1" ] ; then
echo "$(basename $0): open rst2pdf test and reference PDF"
echo "Usage: $(basename $0) "
exit 1
fi
basename=$(basename "$1")
name=$(echo "$basename" | cut -f 1 -d '.')
open "tests/output/$name.pdf" && open "tests/reference/$name.pdf"
Over the course of a few months, this script has gone from a one-liner to a more flexible solution as I’ve seen its value.
I cannot recommend enough this approach enough to command you find yourself running frequently. It makes those tasks easier and more enjoyable.