Claude Code CLI can leave orphaned background processes that consume CPU and memory. This solution automatically kills Claude processes that are no longer attached to a terminal.
Active Claude sessions are attached to a TTY (e.g., s001, s002).
Orphaned processes show ?? in the TTY column. This script kills only the orphaned ones.
Add to ~/.zshrc or ~/.bashrc:
alias claude-cleanup='ps aux | grep "[c]laude" | awk "\$7 == \"??\" {print \$2}" | xargs kill -9 2>/dev/null'Then run claude-cleanup whenever needed.
cat > ~/Library/LaunchAgents/com.user.claude-cleanup.plist << 'PLIST'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.user.claude-cleanup</string>
<key>ProgramArguments</key>
<array>
<string>/bin/bash</string>
<string>-c</string>
<string>ps aux | grep '[c]laude' | awk '$7 == "??" {print $2}' | xargs kill -9 2>/dev/null || true</string>
</array>
<key>StartInterval</key>
<integer>3600</integer>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
PLIST
launchctl load ~/Library/LaunchAgents/com.user.claude-cleanup.plist# Check status
launchctl list | grep claude-cleanup
# Run cleanup manually
launchctl start com.user.claude-cleanup
# Uninstall
launchctl unload ~/Library/LaunchAgents/com.user.claude-cleanup.plist
rm ~/Library/LaunchAgents/com.user.claude-cleanup.plist
# Change interval: edit StartInterval (seconds) in the plist, then unload/load# Count orphaned Claude processes
ps aux | grep '[c]laude' | awk '$7 == "??" {print $2}' | wc -l
# List all Claude processes with their TTY
ps aux | grep '[c]laude' | awk '{print $2, $7, $11}'
💡 A Few Enhancement Tips
Great script! Here are some additional tips that might be helpful:
Customize Cleanup Interval
To change the cleanup frequency (e.g., every 10 minutes instead of hourly):
Quick Cleanup Function
Add this to your
~/.zshrcor~/.bashrcfor a quick manual cleanup command:Then run
source ~/.zshrcand useclaude-cleanupanytime.Protect Long-Running Tasks with tmux
If you run long tasks with Claude and want to prevent accidental termination:
Processes inside tmux have a proper TTY (e.g.,
pts/0), so they won't be flagged as orphaned.Hope this helps! 🙌