From cd3e8631255561d8ab21352b8cb691c05ca47fcb Mon Sep 17 00:00:00 2001 From: Tom Ryder Date: Fri, 12 Feb 2016 16:53:20 +1300 Subject: Add try(1) and maybe(1) --- bin/maybe | 79 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100755 bin/maybe (limited to 'bin/maybe') diff --git a/bin/maybe b/bin/maybe new file mode 100755 index 00000000..2110a959 --- /dev/null +++ b/bin/maybe @@ -0,0 +1,79 @@ +#!/usr/bin/env bash + +# +# maybe(1) -- Like true(1) or false(1); exit with either success or failure +# randomly. Good for basic testing, but doesn't use precise probabilities, just +# fractions of RANDOM's limit. Exits with 2 on usage errors so you can tell the +# difference. +# +# -h gives help, -v gives you stdout specifying success or failure. +# +# Author: Tom Ryder +# Copyright: 2016 +# +self=maybe + +# Print usage information +usage() { + printf '%s: usage: %s [-hv] [-d DENOMINATOR]\n' \ + "$self" "$self" +} + +# Flag for whether to print diagnostics to stdout or not +declare -i verbose +verbose=0 + +# Denominator of the probability fraction, e.g. 3 is a probability of 1/3; +# defaults to 2 +declare -i denom +denom=2 + +# Process options +while getopts 'hvd:' opt ; do + case $opt in + + # -h: Print help + h) + usage + exit 0 + ;; + + # -v: Print diagnostics to stdout + v) + verbose=1 + ;; + + # -d: Set the denominator of the probability fraction + d) + denom=$OPTARG + ;; + + # Unknown option + \?) + usage >&2 + exit 2 + ;; + esac +done +shift "$((OPTIND-1))" + +# If there are any non-option arguments or our denominator isn't a positive +# integer, we're being abused and we won't put up with it +if (($#)) || ! ((denom > 0)) ; then + usage >&2 + exit 2 +fi + +# Perform the test and print/exit appropriately +((verbose)) && printf '%s: Testing with probability 1/%u ... \n' \ + "$self" "$denom" +if ((RANDOM < 32767/denom)) ; then + ((verbose)) && printf '%s: %s\n' \ + "$self" 'Success!' + exit 0 +else + ((verbose)) && printf '%s: %s\n' \ + "$self" 'Failure!' + exit 1 +fi + -- cgit v1.2.3