Skip to content

Instantly share code, notes, and snippets.

@renderorange
Forked from sorbits/every
Created November 1, 2021 17:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save renderorange/f6df8efdb073a887f729afb149c12817 to your computer and use it in GitHub Desktop.
Save renderorange/f6df8efdb073a887f729afb149c12817 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"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment