A backtick inside double quotes ran a Markdown file as a shell script, which ran itself. I moved known mistakes out of the notes and into PreToolUse hooks, then tuned the rules against commands left in past session logs.
This is an English adaptation of an article I originally published in Japanese on Zenn: 1 行のコマンドが自分を呼び続けて PC が固まった。知っている失敗を、実行の前に機械で止める. The measurements and conclusions are mine; I used an AI tool to help translate and restructure the text, and I checked the numbers against the original records. While doing that I found that the original described some counts wrongly (what was counted, not the counts themselves). I corrected the original on November 25, 2026, and this version uses the corrected descriptions.
Short version: a one-line Git Bash command turned into a chain of bash processes calling each other, 1,123 levels deep, and I had to cut the power. The mistake was already in my notes. So I stopped relying on notes and put the checks in a hook that runs right before each command. The rules only became usable after I ran them against commands from past sessions: the first version had 587 rule hits, the tuned one 181.
A 1-minute video summary (narration is synthetic, English captions available):
TL;DR
- I run 10 to 18 Claude Code sessions at the same time on one Windows PC with 32 GB of memory, one per project.
- One session wrote a file name in backticks inside a double-quoted
py -3 -c "...". Bash treats that as command substitution, so it executed the Markdown file. The file contained the same backticked name, so it executed itself again. - Stopping the top process didn't stop the chain. It kept growing to 1,123 nested bash processes and about 47 GB of committed memory.
- I added three things: a hook that blocks backticks that would really be substituted, a hook with nine rules for other known mistakes, and a memory reservation script for large jobs.
- Replayed over 24,374 commands left in recently updated session logs, the rules went from 587 hits to 181. Counted by when the commands were run, 8 of 2,053 commands over two days would have been blocked.
- In the 13 days since, the two hooks have stopped 7 commands for matching a rule, and 5 because the hook itself timed out.
Scope
- Environment: one Windows PC (32 GB), Git Bash and PowerShell, Claude Code. I keep about 30 sessions prepared; 10 to 18 are running at any moment, and one of them coordinates the others.
- Not covered: Linux, macOS, other agents. The rules come from mistakes made on this PC.
What happened
The PC's screen started flickering, and in the end I forced it off.
The cause was one line in Git Bash. A session was passing a short Python script with py -3 -c "...", and inside the double quotes it wrote a file name in backticks, the way you would in Markdown.
# Only the shape; the content is removed
py -3 -c "... `docs/notes.md` ..."
In Bash, backticks inside double quotes are command substitution. `docs/notes.md` isn't text. It means "run docs/notes.md and put its output here". The Markdown file was executed as a shell script.
Unfortunately, that file contained the same `docs/notes.md`. The script that was running ran itself again, and bash kept calling bash.
The command didn't finish, so the session stopped the top process and noted "stopped, no damage". Only the top process had stopped. The bash processes that had lost their parent kept multiplying in the background. By the time I noticed:
| Value | |
|---|---|
| Free memory | 0.6 GB |
| Committed memory / limit | 63.4 GB / 63.5 GB |
| Nested bash processes | 1,123 |
| Memory committed by the chain | about 47 GB |
New processes couldn't start; both bash and PowerShell failed to launch. I had a script ready that would stop only the chain, but I forced the power off before running it.
After the restart, I had the 17 sessions that were running again (not counting the coordinator) check their files. All 17 reported nothing broken and nothing stuck.
It was a known mistake
That backticks in double quotes are substituted is well known to people who use Bash. The AI knows it too. It still happens when it thinks it's writing a Python string and the Markdown habit slips in.
It also wasn't a one-off. I took the session logs that had been updated in the previous three days, pulled out every command containing a backtick (2,808, including old ones, since the logs go back further), and ran them through the hook I'd write later. It found 17 with the same shape: a backtick at a position where Bash substitutes it, such as inside double quotes. The accident itself isn't among them, and none of them turned into one like it. Counted by when they were run, it was 2 of 3,035 Bash commands in three days, and one of those two was the accident.
Around that time I'd asked each session to write down its failures of the past month, and 20 sessions had contributed to one list. It had more mistakes of the same kind, known but still made:
-
> nulin Git Bash creates a file namednul, which is awkward to delete -
$_for PowerShell inside Bash double quotes is emptied by Bash before PowerShell sees it - Checking whether a server is listening with
-State Listenor by looking forLISTENin netstat: on this PC, since some point in early November, it comes back empty even when the server is up (I suspect a Windows update, but haven't confirmed the cause) - Stopping a process by name, such as
python.exe, also stops the Python of other sessions -
rm -rf $DIR/...with a variable that might be empty
Every session could read the list. It wasn't enough: when in a hurry, they still made the mistakes.
So I stopped relying on reading, and had a script check each command right before it runs. Claude Code can run a script before a tool call (a PreToolUse hook). The script receives the command string and can block it or let it through.
Guard 1: backticks
The first hook blocks what caused the accident. It looks for backticks at positions where Bash would really substitute them, and blocks only those.
That restriction matters. Blocking every backtick would stop ordinary work. These pass:
- Inside single quotes
'...'(no substitution) - Inside a heredoc with a quoted delimiter,
<<'EOF'(no substitution) - After
#, in a comment
When it blocks a command, it returns the reason and the fix: write Python to a file and run the file, use single quotes for strings, or use $( ) if you do want substitution.
I wrote 15 test cases that should be blocked or passed, with zero wrong answers. The 17 above come from running it over those 2,808 commands. The script printed only the first 12 matches, so I didn't check all 17 one by one.
Guard 2: the list of known mistakes
I did the same for other items on the list. This hook had nine rules when I wrote the original article, and checks both Bash and PowerShell commands.
| Rule | What it blocks | Fix |
|---|---|---|
nul-redirect |
> nul in Git Bash |
/dev/null |
ps-dollar-in-bash-dq |
PowerShell $_, $env: or assignments inside Bash double quotes |
Single quotes, or a .ps1 file with -File
|
wsl-dollar-in-bash-dq |
$variable in double quotes passed to wsl (expanded on the Windows side first) |
Single quotes, or pass the value as an argument |
rm-rf-unguarded-var |
rm -rf with a possibly empty variable |
${X:?}, which stops if it's empty |
listen-state |
Checking for a listening port with -State Listen or LISTEN
|
Look up connections by port and find the one whose remote port is 0 |
kill-by-name |
Stopping a process by name | Stop it by pid |
winget-upgrade-all |
winget upgrade --all (on this PC winget mistakes one app for another, so upgrading everything may overwrite it) |
One at a time with --id
|
borrowed-repo-push |
git push in the repository of a tool I'm borrowing from someone |
Don't push |
printf-winpath |
C:\Users in a printf format (\U is read as an escape) |
Use %s and pass the path as an argument |
Sometimes you mean it. Adding # pitfall-ok:<rule> to the end of the command lets it through. I included that from the start.
The core of the matching is not looking inside quotes. If echo "> nul" were blocked, explanations and git commit -m messages would be blocked too. So most rules first pass the command through this function:
function outsideQuotes(cmd) {
let out = "", st = "n";
for (let i = 0; i < cmd.length; i++) {
const c = cmd[i];
if (st === "s") { if (c === "'") st = "n"; out += c === "\n" ? "\n" : " "; continue; }
if (st === "d") {
if (c === "\\") { out += " "; i++; continue; }
if (c === '"') st = "n";
out += c === "\n" ? "\n" : " "; continue;
}
if (c === "'") st = "s"; else if (c === '"') st = "d";
out += c;
}
return out;
}
It replaces everything inside single and double quotes with the same number of spaces. Newlines stay, so lines and positions don't shift. Only > nul or git push outside quotes remains for the rule's regex. Inside double quotes, \" is skipped as two characters so it isn't taken for the closing quote.
Some rules do need to look inside the quotes. PowerShell's $_ in Bash double quotes, and $variable passed to wsl, are problems precisely because of the quotes, so those rules don't use this function.
Tuning against commands that were really run
Writing rules is easy. If they block too much, work stops. So I test in two stages.
- Examples: cases to block and cases to pass, per rule. There were 62 when I wrote the original, with zero wrong answers.
- Replay: take the session logs updated in the last two days, extract every command in them (including old ones), run the rules over them, and count rule hits.
The first version had 587 hits (over 24,338 commands). Many of them didn't need blocking:
- The body of a heredoc (text being written to a file, not executed)
-
git stash push(it reacted to the wordpush) -
rm -rfwith a variable that had just been assigned - A variable from
for v in ...passed to wsl
After letting those through, there were 181 hits over 24,374 commands. The script prints up to four examples per rule; I have no record of checking every hit.
| Rule | Count |
|---|---|
| Checking for listening ports with LISTEN | 129 |
| Stopping a process by name | 32 |
PowerShell $_ etc. in Bash double quotes |
17 |
rm -rf with a possibly empty variable |
2 |
git push in the borrowed repository |
1 |
These logs go back further than two days. Counting only commands run in the two days before the hook went in, 8 of 2,053 would have been blocked: 4, 1 and 3 for the first three rows.
The top one surprised me. Every session starts servers and checks whether they're up, and they kept using the method my list says doesn't work on this PC.
The hook makes no network calls. Each check takes about 0.1 seconds, and I haven't noticed a difference in how fast work goes.
Guard 3: memory reservations
The third isn't about how a command is written, but about memory.
Different sessions on this PC run image generation (ComfyUI), local LLMs, and embedding servers, which use from a few GB to almost 20 GB. If they don't know about each other, two can start at once and run out. Before the accident, one session had started an embedding server (4 GB), and right after that another started ComfyUI (16 GB), and the SSD was pinned.
So I wrote a script that reserves memory before a large job starts.
python heavy_lease.py acquire --gb 18 --what "ComfyUI 8188" --session image
- The decision subtracts what other reservations are still going to grow into. ComfyUI is small until it loads a model, so looking only at free memory now means running out later.
- A reservation is tied to the process of the session that asked for it. When the process goes away, so does the reservation.
- The ledger is written under a lock. If it's corrupted, it's moved aside and a warning is shown.
-
statusshows current reservations and processes using 2 GB or more without one, with their command lines.
I didn't add a permanent monitor. If every session reserves first, this was enough.
What changed in the first five days
From "let it through" to "block" when the hook breaks. At first, if the hook itself failed (no node, a crash, a timeout), the command went through, because I didn't want a broken hook to stop all work. But then a guard could disappear without anyone noticing. Now a hook that fails blocks the command, using "onFailure": "block" in the hook settings (documented for Claude Code v2.1.295 or later; by default the action goes ahead when a hook fails). My notes say that if every Bash command is blocked, suspect the hook first.
From free memory to a pinned SSD. At first I stopped a job when free memory fell below 1 GB. Then I looked at the log of a run that generated 24 images. Free memory dropped to 1.3 GB, but page file usage rose by only 0.4 percentage points. Averaged over 60 seconds, the SSD wasn't pinned at any point. What I want to avoid isn't low memory. It's heavy paging that pins the SSD and slows down the whole PC.
So when no other large job is running, a job may start even without enough free memory, with a script watching the SSD. Leaving out the two minutes of model loading, it stops the job if disk use over the last 60 seconds averages above 90% and page file usage has risen by more than 0.3 percentage points. When jobs compete, they still queue for a reservation.
13 days later
I counted again by when each command was run, on this PC only (8,522 Bash calls for the second hook):
| Backtick hook | Known-mistakes hook | |
|---|---|---|
| Blocked by a rule | 3 | 4 (PowerShell $_ etc. 2, winpath-backslash-in-code 2, the rule added later) |
| Blocked by the 10-second timeout | 2 | 3 |
Let through with # pitfall-ok
|
n/a | 3 (all listen-state) |
Commands I ran only to test the hooks are left out. The hooks block little; I can't count how often a session avoided a mistake because it had read the rule. The timeouts are "onFailure": "block" doing its job: the command didn't run.
There are ten rules now. The tenth, winpath-backslash-in-code, blocks Windows paths with backslashes inside sed or Python strings without r. The examples went from 62 to 77, still with zero wrong answers.
Where this stops
- I don't know whether it has prevented the same accident. The same kind of command has been blocked since, but I can't tell whether it would have turned into an accident.
- Other environments. I only check Git Bash and PowerShell on Windows, with rules from this PC's list. I haven't tried Linux or macOS shells.
- The replay numbers can't be reproduced exactly. They depend on which logs had been updated at that moment, and those logs have grown since.
Takeaways
- Writing a rule down isn't enough when someone's in a hurry, AI or human. The list was correct, and the accident still happened.
- Draw the line with records of what was really run. My first rules had 587 hits. Letting through the forms that didn't need blocking brought that to 181. The work logs became the test data. Also write down what was counted: I first described these numbers wrongly, as commands run in two or three days.
-
If you block, also provide a way through. Without
# pitfall-ok, someone with a good reason would look for a detour, and I'd no longer see what they did. - Something that calls itself doesn't end when you stop the top. Afterwards, check how many bash processes remain and who their parents are.
The original of this article: 1 行のコマンドが自分を呼び続けて PC が固まった。知っている失敗を、実行の前に機械で止める.
Top comments (17)
Replaying the rules over old commands before trusting them is the part I'd copy. A related trap sits on the hook entry itself rather than the commands it checks: if a hook runs inline PowerShell, Git Bash expands the $ before PowerShell sees it, same family as your ps-dollar-in-bash-dq rule. The exec form (command plus an args array, pointing at a .ps1 file) skips the shell entirely. I also keep those scripts ASCII-only, because Windows PowerShell 5.1 reads a file without a BOM as ANSI, and one typographic dash inside a string was enough to break the parse for me. Are your hooks in shell form or exec form?
Shell form, but nothing in the hook entry gets expanded. Each entry is just node with a quoted path to a .mjs file, e.g. node "C:/Users//.claude/hooks/pitfall-guard.mjs", and the command to check arrives as JSON on stdin. So no inline PowerShell, and no $ for Git Bash to touch. Thanks for the BOM tip; my scripts are JavaScript with Japanese text in them, which Node reads as UTF-8 without trouble, but it's worth keeping in mind for any .ps1.
That's the safe version, nothing left for Bash to expand. The part I didn't expect is what the shell itself costs per call. I timed one hook on Windows: the program alone took 16 ms, through Git Bash 42 ms, through cmd /c 45 ms, and through PowerShell 418 ms. Shell form goes through Git Bash every time, so the exec form ("command": "node" plus the .mjs path in "args") would drop roughly 25 ms from each of your 8,522 calls. Node's own startup is probably most of your 0.1 s, though.
Thanks for timing it. All I have is the total, about 0.1 s per check, so I can't say how much of it is Node's startup and how much is the shell. That's worth timing before I change anything.
Easy way to split it: time
node -e "0"on its own, which is the startup floor, then your hook script with a sample JSON piped to stdin, then the same call through the real hook entry. In my test the bare program was 16 ms and Git Bash added about 26 ms on top, so if most of your 0.1 s is the first number, switching to exec form won't change much. Curious what you find.Replaying the rules over 24,374 old commands before trusting them is the step most hook write-ups skip, and the drop from 587 hits to 181 shows why it matters. You say the hook returns the reason and the fix. Is that exit code 2 with the text on stderr? For a PreToolUse hook, Claude Code feeds that stderr back to the model, so the agent can retry with single quotes or a file for the
py -3 -cbody instead of stopping cold. We would be curious how many of the 7 got a working retry on the next turn and how many needed you.Yes. Both hooks write the reason and the fix to stderr and exit with code 2, and Claude Code passes that text back to the model as the result of the blocked call.
I hadn't counted the retries, so I went back to the session logs for those 7 blocks. Every one was followed by a working command within 3 to 12 seconds, with no message from me in between:
$_case moved the command into a .ps1 file.So none of the 7 needed me. "Working" here means the next command ran and returned the output it was after; I read each pair, but it's 7 cases on one PC, so I wouldn't read much into the rate.
Running the rules against commands from past sessions is the part worth copying. Going from 587 hits to 181 shows that a hook is only as useful as its false-positive rate, since noisy blocks tend to get switched off. One addition: keep the replayed commands as a small must-block and must-allow list and re-run it whenever you edit a rule, so a tweak that quiets a noisy pattern doesn't quietly reopen the original hole.
Agreed, and that's roughly what I ended up with. The forms the replay showed didn't need blocking (heredoc bodies, git stash push, a for-loop variable passed to wsl) became must-allow cases, next to the must-block ones. There are 77 examples now, and I run them before installing any rule change. The full replay is a separate option on the same test script.
1,123 nested bash processes is the kind of number that makes you laugh and then immediately check your own setup. The line that stuck with me is 'writing a rule down isn't enough when someone's in a hurry' — that's true of humans too, not just agents, and it's why the hook-before-execution approach feels right. The replay tuning is the part I'd copy though: 587 hits down to 181 by letting through the forms that didn't need blocking. Did the 10-second timeout blocks ever bite you on a legitimately slow command, or has that been quiet so far?
The 10 seconds is a limit on the hook, not on the command, so a slow command never runs into it: the hook only reads the command string and answers before the command starts. It has fired 5 times in those 13 days, each time because the hook itself didn't finish within 10 seconds. I haven't looked into why those particular calls were slow. The command was blocked without running. In 4 of the 5 the session ran it again, or a simpler version of it, on its next call and it went through; in the other it moved on to a different check. Since the article's 13 days it has happened twice more, back to back in one session: the second call was a smaller command, and when it was blocked too, the same smaller command went through on the next call. So it has cost a retry now and then, but nothing has been lost so far.
The notes part is what got me. You had the mistake written down, the list was right there for every one of them to read, and it still happened, because reading is not the same as stopping. I hit the same wall from the other side: my agent kept fixing things nobody asked it to fix, renaming a function here, rewriting a file to fix one line there, and I spent the afternoon undoing the extra work. Writing the rule down helped, but only once the rule said exactly what "done" means. The one I reach for first says change the smallest amount of code that fixes the problem properly, not the smallest amount that makes the test pass. One change, one reason. A bug fix does not also rename variables. I tried it on three small demo projects before trusting it, and the clearest before and after was a Node program that used to die on a missing config file with a raw stack dump and now exits with one plain sentence naming the problem and the fix. The full rule is free to read if it helps: aheadkit.me/free-samples/lean-code...
Which of your nine rules was the hardest to tune without it blocking real work? The listening-port one at 129 hits looks like the one that would have driven me mad.
I never changed the listen-state rule itself. Its 129 hits weren't false alarms: they were sessions really checking a server with the method that comes back empty on this PC. In the 13 days I counted, sessions let it through 3 times with # pitfall-ok, when they meant to use it. The tuning was about forms that didn't need blocking at all, across the rules: heredoc bodies, git stash push, rm -rf with a variable assigned just before it, and a for variable passed to wsl. It's ten rules now; the tenth blocks Windows paths with backslashes inside sed or Python strings.
Moving known mistakes out of the notes and into something that runs before the command is the step most people never take: a note is advice the agent can skip. "I can't count how often a session avoided a mistake because it had read the rule" is honest, and it's the right limit to name. The next thing we'd want is for the list to travel. In Halfcycle the cause and the fix from one project reach every other project automatically, so most of these never show up again and the rest arrive with the answer attached. If you try npx halfcycle on a Windows project, we'd like to know what it misses that your ten rules catch.
A PreToolUse hook is a local check, so the rule itself costs no model tokens. What it prints back is what the model reads, so keep the message short.
Agreed. Mine are four lines each: what matched and why it's a problem, the fix, and then either the
# pitfall-okway through or, in the backtick hook, a line about the original accident. That last one I could probably drop.1,123 nested bash processes would have left my own PC with no memory to spare.