From 48374cb189a58ab6a44871c7c744a1f67f986089 Mon Sep 17 00:00:00 2001 From: Armaan Bhojwani Date: Tue, 2 Mar 2021 12:41:50 -0500 Subject: [PATCH] fortune: add max/min length options Also change the way the cookies are found --- fortune | 69 ++++++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 49 insertions(+), 20 deletions(-) diff --git a/fortune b/fortune index 5030086..a8589a5 100755 --- a/fortune +++ b/fortune @@ -1,38 +1,51 @@ #!/usr/bin/sh -e -# Fortune implementation in awk +# Fortune implementation in POSIX sh/awk -usage() -{ - echo "Usage: fortune [OPTIONS] +usage() { + echo 'Usage: fortune [OPTIONS] a simple POSIX sh/awk implementation of fortune - -h, --help show this help message - -l, --list list cookie files installed to /usr/share/fortune/ - -f \$FILE, --file \$FILE specify full path to cookie file - -c \$FILE, --cookie \$FILE specify path to cookie file relative - to /usr/share/fortune/ -" + -h, --help show this help message + -l, --list list installed cookie files + -c FILE, --cookie FILE specify cookie file + -n LENGTH, --min LENGTH specify min fortune length + -N LENGTH, --max LENGTH specify max fortune length + + fortune looks for fortunes in $FORTUNEDIR, which defaults to + /usr/share/fortune. + +Exit codes: + 0 success + 1 argument error + 2 parse error' } -FILE="$(find /usr/share/fortune/ -type f -not -name '*.dat')" +DIR=${FORTUNEDIR:-"/usr/share/fortune/"} +FILE="$(find $DIR -type f -not -name '*.dat')" +MAXLENGTH=1000000000000 +MINLENGTH=0 + while [ "$1" != "" ]; do case $1 in -h | --help) usage exit ;; - -f | --file) - FILE=$2 - ;; -c | --cookie) - FILE=/usr/share/fortune/$2 + FILE=$DIR/$2 + ;; + -n | --min) + MINLENGTH=$2 + ;; + -N | --max) + MAXLENGTH=$2 ;; -l | --list) - ls -1 /usr/share/fortune + ls -1 $DIR exit ;; *) - echo "ERROR: unknown parameter \"$2\"" + echo "ERROR: unknown option \"$1\"" usage exit 1 ;; @@ -40,12 +53,28 @@ while [ "$1" != "" ]; do shift 2 done -awk 'BEGIN { +[ "$MAXLENGTH" -lt "$MINLENGTH" ] && { + echo "ERROR: maximum length is less than minimum length" + exit 2 +} + +[ -d "$FILE" ] && { + echo "ERROR: directory given, please provide a file or glob of files" + exit 2 +} + +awk -v maxlen=$MAXLENGTH -v minlen=$MINLENGTH \ +'BEGIN { f++ } $1 == "%" { - f++ + len = length(fortunes[f]) + if ( len>maxlen || len