]> git.armaanb.net Git - bin.git/blob - fortune
fortune: Add argument parsing
[bin.git] / fortune
1 #!/usr/bin/sh -e
2 # Fortune implementation in awk
3
4 usage()
5 {
6     echo "fortune -- a simple awk/POSIX sh implementation of fortune"
7     echo ""
8     echo "\t-h --help     show this help message"
9     echo "\t--file=\$FILE  specify path to cookie file"
10 }
11
12 FILE="$(find /usr/share/fortune/ -type f -not -name '*.dat')"
13 while [ "$1" != "" ]; do
14   PARAM=`echo $1 | awk -F= '{print $1}'`
15   VALUE=`echo $1 | awk -F= '{print $2}'`
16   case $PARAM in
17       -h | --help)
18           usage
19           exit
20           ;;
21       -f | --file)
22           FILE=$VALUE
23           ;;
24       *)
25           echo "ERROR: unknown parameter \"$PARAM\""
26           usage
27           exit 1
28           ;;
29   esac
30   shift
31 done
32
33 awk '$1 == "%" {
34   sub(/%/, "")
35   ++f
36 }
37
38 {
39   fortunes[f] = fortunes[f] (length(fortunes[f])?"\n":"") $0
40 }
41
42 END {
43   "date +%N" | getline time
44   srand(time)
45   print fortunes[int(rand() * f) + 1]
46 }' $FILE