Created
October 26, 2026 21:48
-
-
Save blixt/8ab93f54107d7243cc165f207c2d02b8 to your computer and use it in GitHub Desktop.
pkill guard to stop Claude/Codex from pkilling your computer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| pkill() { | |
| local -a rest=("$@") others=() | |
| local arg letters i seen_pattern=0 ended=0 want_value=0 | |
| # A leading -9, -KILL or -SIGTERM is pkill's own; pgrep takes no signal. | |
| local sig=${${rest[1]#-}#SIG} | |
| if [[ ${rest[1]} == -* && ( $sig == <-> || ${${(s: :)$(kill -l)}[(Ie)$sig]} -gt 0 ) ]]; then | |
| rest=("${(@)rest[2,-1]}") | |
| fi | |
| # Read the arguments as BSD getopt does. These letters take a value. | |
| local valued=FGMNPTUcdgjstu | |
| for arg in "${rest[@]}"; do | |
| if (( want_value )); then want_value=0; continue; fi | |
| if (( ended )); then seen_pattern=1; continue; fi | |
| if [[ $arg == -- ]]; then ended=1; continue; fi | |
| if [[ $arg == -?* ]]; then | |
| if (( seen_pattern )); then | |
| print -u2 "pkill: refused: '$arg' comes after the pattern, so macOS reads it as one more pattern. Put every option before the pattern." | |
| return 2 | |
| fi | |
| letters=${arg#-} | |
| for (( i = 1; i <= ${#letters}; i++ )); do | |
| if [[ $valued == *${letters[i]}* ]]; then | |
| (( i == ${#letters} )) && want_value=1 | |
| break | |
| fi | |
| done | |
| else | |
| seen_pattern=1 | |
| fi | |
| done | |
| # Ask the real pgrep what the same arguments match (-I is pkill-only). | |
| local -a pids=(${(f)"$(command pgrep "${(@)rest:#-I}")"}) | |
| local pid | |
| for pid in $pids; do | |
| # Own = the process carries this chat's COCE_CHAT_ID in its environment. | |
| if [[ -n $COCE_CHAT_ID ]] && | |
| [[ $(ps eww -o command= -p $pid 2>/dev/null) == *"COCE_CHAT_ID=$COCE_CHAT_ID"* ]]; then | |
| continue | |
| fi | |
| others+=($pid) | |
| done | |
| if (( ${#others} > 1 )); then | |
| print -u2 "pkill: refused: this pattern matches ${#others} processes this chat did not start, and one pkill stops at most one of them. Kill exact pids instead:" | |
| ps -o pid=,command= -p ${(j:,:)others} | cut -c1-120 >&2 | |
| return 2 | |
| fi | |
| command pkill "$@" | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment