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