Skip to content

Instantly share code, notes, and snippets.

@sorbits
Last active July 4, 2024 03:28
Show Gist options
  • Save sorbits/5c0cb7292de091253f8e to your computer and use it in GitHub Desktop.
Save sorbits/5c0cb7292de091253f8e to your computer and use it in GitHub Desktop.
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"
Copy link

ghost commented Apr 30, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment