Create a gist now

Instantly share code, notes, and snippets.

@sorbits /every
Last active Aug 13, 2017

What would you like to do?
Run «command» only every «number» time invoked
#!/usr/bin/env bash
progname=$(basename $0)
version="1.0 (2014-08-17)"
step=2
function create_hash {
openssl dgst -sha1 -binary <<< "$1" | xxd -p
}
while getopts ':n:vh' opt; do
case $opt in
n) step=$OPTARG ;;
v) echo "$progname $version"; exit ;;
:) echo >&2 "$progname: option requires an argument -- $OPTARG"; exit 1 ;;
\?) echo >&2 "$progname: illegal option: -- $OPTARG"; exit 1 ;;
h)
echo "$progname $version"
echo "Usage: $progname [-n number] command [argument ...]"
echo " $progname [-v|-h]"
echo "Options:"
echo " -n <number> Run every <number> time. Defaults to 2."
echo " -v Print version information."
echo " -h Show this information."
exit
;;
esac
done
if [ $OPTIND -gt $# ]; then
echo >&2 "$progname: no command specified. Use -h for usage options."
exit 1
fi
file="${XDG_DATA_HOME:-$HOME/.local/share}/${progname}/$(create_hash "$*")"
if [ ! -f "$file" ]; then
mkdir -p "$(dirname "$file")"
echo >"$file" 1
fi
value=$(head -n1 "$file")
if [ $value -ge $step ]; then
rm "$file"
exec "${@:$OPTIND}"
fi
printf "%d\n# Last run: %s\n# Command: %s\n" "$(( $value + 1 ))" "$(date)" "${*:$OPTIND}" >"$file"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment