Archive for August, 2007

Parsing parameters in bash - a getopt template

Thursday, August 16th, 2007

Writing some bash scripts that parse command lines, I wrote this handy template with getopt. It is easy to apply even for simplest scripts.

OPTION_SPEC="help,flag1,flag2_params:"
PARSED_OPTIONS=$(getopt -n "$0" -a -o h --long $OPTION_SPEC -- "$@")
OPTIONS_RET=$?
eval set -- "$PARSED_OPTIONS"

Parsing error or no flags

if [ $OPTIONS_RET -ne 0 ] || [ $# -le 0 ]; then usage; die; fi

while [ $# -ge 1 ]; do case $1 in --help | -h ) usage; die;; --flag1 ) FLAG1=1;; --flag2_params ) shift; FLAG2_PARAMS="$1";; -- ) shift;; * ) echo "ERROR: unknown flag $1"; usage; die;; esac shift done

No more unannotated $ns in my scripts!

Date of yesterday in bash?

Thursday, August 16th, 2007

I recently had to hack a small shell script that would read files in a directory structure generated based on the date, something like 2007/08/16. The trick was that the script would look at yesterday’s file or files generated a few days ago.

A quick search on info and here’s the magic command

FILE="...$(date -d 'yesterday' +%Y/%m/%d)"

Interestingly, you can also use things like 3 days ago, next Monday, 2 months etc. Cool!