Friday, November 21, 2008

Bash menu script

I long had a csh script that reads a '.choices' file in each directory, display the choices, and execute my choice. Well, i've migrated away from csh and no longer have it on many of my machines. So, i wrote the following:
#! /bin/bash -e

filename=".choices"

if [ "$1" == "-f" ]
then
    filename="$2"
    shift
    shift
elif [ ! -r $filename ]
then
    prefix=.
    while true
    do
        absolute=$(cd $prefix; pwd)

        if [ -r $absolute/$filename ]
        then
            filename=$absolute/$filename
            break
        fi

        if [ $absolute = "/" ]
        then
            echo "No .choices file found, exiting"
            exit 1
        fi

        prefix=$prefix/..
    done
fi

if [ "$1" != "" ]
then
    a=$1
    shift
    echo `sed -ne "$a,$a p" $filename` $*
    eval `sed -ne "$a,$a p" $filename` $*
    exit
fi

IFS=$'\n'

select CHOICE in `cat $filename`
do
    eval $CHOICE $*
    break
done
 

This wasn't as easy as it looks. Getting bash to create a single word for the select statement from lines in a file. Finding the right incantation for the IFS was the tricky part...

No comments: