
You can restrict how often a command executes by remembering its last execution time.
Recently, I've been adding pre-command hooks in my dotfiles to auto-update various tools before executing them. Many tools can auto-update themselves, but many still can't.

Automatically Execute Code Before & After Unix Commands
Jan 19, 2023 · 4 min read
It can be helpful to run some code automatically before or after calling a command, and it is easy to accomplish with shadowing functions.
The hooks have been working great, but I launch some of these tools many times in a day, and I don't want to pay the cost of attempting an update on every launch. So I created a Bash function in my dotfiles that can "throttle" commands:
1# @param {string} $1 Name of the throttle key
2# @param {number} $2 Cooldown duration in seconds
3throttle() {
4 local state_dir="${XDG_STATE_HOME:-${HOME}/.local/state}/throttle"
5 local state_file="${state_dir}/$1"
6 local now
7 now=$(date +%s)
8 local last_run=0
9 if [[ -f "${state_file}" ]]; then
10 last_run=$(cat "${state_file}" 2>/dev/null || echo 0)
11 fi
12 if (( now - last_run > $2 )); then
13 mkdir -p "${state_dir}"
14 echo "${now}" > "${state_file}"
15 return 0
16 fi
17 return 1
18}
The function remembers the last time your user called it with a specific "key" by storing a timestamp in a state file. Each command that you want to throttle should have its own key, decided by you.
Here are some contrived usage examples:
1# Print "hello world" at most every 60sec
2if throttle "ECHO_HELLO_WORLD_SECS" 60; then
3 echo "Hello world!"
4fi
1# Update all Homebrew packages every 12hrs
2if throttle "BREW_AUTO_UPDATE_SECS" 43200; then
3 brew update
4fi
1# Self-update npm every 48hrs
2if throttle "NPM_AUTO_UPDATE_SECS" 172800; then
3 npm install --global npm@latest
4fi
Real-world example
Claude Code only auto-updates "native" installations, which were introduced in v2.0 (2025). Before that, you had to update it manually via npm, Homebrew, or whatever package manager you used to install it. You can still use a package manager to install Claude Code, though they don't recommend it anymore.
Here's an example usage of the throttle function that will occasionally auto-update Claude Code before it's started:
1if command -v claude &> /dev/null; then
2 claude() {
3 # Update Claude Code once every 24hrs
4 if throttle "CLAUDE_AUTO_UPDATE_SECS" 86400; then
5 if npm list --global @anthropic-ai/claude-code > /dev/null; then
6 # Update the npm installation
7 npm update --global @anthropic-ai/claude-code
8 elif command -v brew &> /dev/null && brew list claude-code &> /dev/null; then
9 # Update the Homebrew installation
10 brew upgrade claude-code
11 else
12 # Self-update (requires v2.0+)
13 command claude update
14 fi
15 fi
16
17 command claude "$@"
18 return $?
19 }
20fi



