claude-code icon indicating copy to clipboard operation
claude-code copied to clipboard

Windows/Git Bash: Bash tool silently halves backslashes in commands (MSVCRT vs MSYS2 command-line encoding mismatch)

Open momom2 opened this issue 3 months ago • 22 comments

Bug report: Bash tool silently halves backslashes on Windows (Git Bash / MSYS2)

Summary

On Windows with Git Bash, every run of backslashes in a Bash tool command is halved before bash parses anything: n backslashes arrive as ceil(n/2). Quoting cannot prevent it — single quotes, double quotes and quoted heredocs (<<'EOF') are all affected identically, because the corruption happens at process-spawn time, before bash lexes a single character.

Cause: Claude Code encodes its command line with MSVCRT quoting rules, but the target (bash.exe) is an MSYS2 binary that decodes with a different convention. MSYS2 performs an un-escaping pass that Claude Code never escaped for, so one backslash is eaten from every pair.

Severity

Two failure modes, and the second is the concerning one:

# loud - fails immediately
"C:\\Users\\x"  ->  "C:\Users\x"  ->  SyntaxError: (unicode error)
                                      truncated \UXXXXXXXX escape

# SILENT - exit code 0, wrong result
print("a\\nb")  ->  print("a\nb")  ->  prints a real newline

Single backslashes survive, so raw-string regexes like r"\s+" keep working. That masks the bug until a Windows path or a literal escape appears, and it means agents can produce silently wrong output with no diagnostic.

This affects any heredoc'd or inlined content containing backslashes — Python, sed, awk, jq, LaTeX — not just Python.

Environment

  • Windows 11 Home 10.0.26200
  • Claude Code 2.1.222 (AppData\Roaming\Claude\claude-code\2.1.222\claude.exe)
  • Git for Windows bash 5.3.15(1)-release, MSYS2 runtime 3.6.9
  • Python 3.13.14

Reproduction A — through Claude Code

Run as a Bash tool command:

printf '%s\n' 'a\\b'
  • Expected: a\\b (bash single quotes are literal; nothing should change)
  • Actual: a\b

Reproduction B — standalone, isolates the layer

Does not involve Claude Code. Sends a byte-exact Windows command line from a native process, so nothing but MSYS2 can alter it:

import subprocess, re

BASH = r"C:\Program Files\Git\bin\bash.exe"
inner = r"printf '%s' 'A:\ B:\\ C:\\\ D:\\\\'"   # runs of 1,2,3,4
cmdline = '"' + BASH + '" -c "' + inner + '"'

out = subprocess.run(cmdline, capture_output=True).stdout.decode()
print("sent    :", [len(s) for s in re.findall(r"\\+", inner)])
print("received:", [len(s) for s in re.findall(r"\\+", out)])
sent    : [1, 2, 3, 4]
received: [1, 1, 2, 2]

The payload is inside bash single quotes, where bash performs no processing whatsoever. The loss is therefore not bash's.

Root cause

Windows passes a command string, not an argv array, so spawner and spawnee must agree on how to parse it. They don't:

convention for a double-quoted argument
Claude Code (and every native spawner: Node, PowerShell, CPython) MSVCRT: backslashes literal, except doubled immediately before a quote
bash.exe (MSYS2 runtime) \\ → \, \" → "

MSYS2 runs an extra un-escaping pass the sender never escaped for.

Confirmed by reading the live command line of the spawned bash via Get-CimInstance Win32_Process. Claude Code's encoding is correct MSVCRT — a run of 4 backslashes before a quote was correctly emitted as 8. The mismatch is purely in which convention the receiver applies.

The trigger is specifically double-quoted arguments. Bare arguments are untouched:

command line MSYS2 bash native MSVCRT receiver
bare a\b a\\b a\\\b a\\\\b 1,2,3,4 ✓ 1,2,3,4 ✓
quoted "a\b" "a\\b" … 1,1,2,2 ✗ 1,2,3,4 ✓

Since the Bash tool's command contains spaces, it is always passed as one double-quoted -c argument — i.e. always in the failing cell.

Proposed fix

When the spawn target is an MSYS2/Cygwin binary, encode arguments for its convention rather than MSVCRT's:

// inside the double-quoted argument
const msys2Encode = (arg) => arg.replace(/\\/g, '\\\\').replace(/"/g, '\\"');

Must be conditional on the target. Applying this to a native Windows executable breaks it in the opposite direction: MSVCRT treats backslashes as literal, so C:\Users would arrive as C:\\Users.

Verification of the proposed encoder

Measured against the current MSVCRT encoding, same inputs, same invocation shape (including the eval '...' wrapper Claude Code uses):

test current encoding proposed encoding
11-case behaviour battery 4 failures 0 failures
800 fuzzed payloads (quotes, spaces, $, backtick, glob metachars) 21 mismatches 0 mismatches
non-ASCII (accents, CJK, Greek, emoji) correct correct
quoted args with spaces, python3 -c, globbing correct correct

It is a strict improvement: every case that works today still works, and the backslash failures are fixed.

What does not work

MSYS=noglob restores backslashes but disables the entire quote-unescaping pass, including \". Since a native spawner must encode inner quotes as \", every command containing a double quote then breaks:

echo "result: ok"              ->  result:
python3 -c "print('hi there')" ->  bash: syntax error near unexpected token `('

Please don't ship that as a workaround.

Workaround for users

Write the script to a file (the Write tool is byte-faithful) and run the file. The Write tool, the PowerShell tool, script files and bash→bash spawns are all unaffected; only the Windows→MSYS2 command line corrupts.

momom2 avatar Aug 11 '26 16:08 momom2

Independently confirmed, and one datapoint for the root-cause analysis: the collapse reproduces byte-for-byte on Git for Windows 2.55.0.4 (bash 5.3.15, msys 3.6.9) with Claude Code 2.1.236 — runs of 2/4/8 backslashes arrive as 1/2/4, in single quotes and quoted heredocs alike. Upgrading Git changes nothing, so this is the harness's spawn encoding, as you diagnosed. (For contrast: the sibling non-ASCII → exit 127 failure on old Git is cured by the Git upgrade — different layer.)

Until the spawn path is fixed I published hooks that guard the class: PreToolUse denies commands carrying a collapsing run and points the model at write-a-file-and-pass-the-path; PostToolUse/PostToolUseFailure flags mangled output so the model doesn't trust the side effects. Corpus of real mangled commands as the test suite: https://github.com/borisbat/hooks-and-memes

borisbat avatar Aug 20 '26 02:08 borisbat

Independent confirmation on a second environment, plus your test corpus run here.

Repro A, byte-exact (Bash tool command): printf '%s\n' 'a\\b' prints a\b.

Runs 1–6, single-quoted payload, printf '%s' vehicle — immune to echo escape interpretation by construction:

sent     : B1:\  B2:\\  B3:\\\  B4:\\\\  B5:\\\\\  B6:\\\\\\
received : B1:\  B2:\   B3:\\   B4:\\    B5:\\\    B6:\\\

1,2,3,4,5,6 → 1,1,2,2,3,3 — exactly ceil(n/2), extending the issue's 1–4 table to 6. An earlier pass with echo gave the same six values, with the escape-interpretation confound ruled out separately (echo 'x\ny' prints literally on this box; xpg_echo unset).

Corpus: cloned the repo and ran tests/test_bash_mangling.py on this environment — 57/57 pass.

Environment:

Claude Code      2.1.234 (version of the live runtime process that ran the probes)
bash             GNU bash 5.2.37(1)-release
Git for Windows  git 2.52.0.windows.1
OS               Windows 11, 10.0.26200
Python           3.14.3

Version spread on the collapse so far: your report (Claude Code 2.1.222, bash 5.3.15 / msys 3.6.9), your re-probe (Git for Windows 2.55.0.4, Claude Code 2.1.236, per the hooks-and-memes README), and this box (Git for Windows 2.52.0, Claude Code 2.1.234) — byte-identical in all three, consistent with the harness spawn encoding rather than anything on Git's side.

Mitigation running locally since today, for anyone landing here meanwhile: bash_mangling_rules.py wired behind a PreToolUse deny and a PostToolUse detector (registered for both result events — a nonzero Bash exit routes through PostToolUseFailure, verified live on 2.1.234, as the repo README documents). The PROBE_MODE toggle is what let the measurements above run through the very gate that now denies such commands.

Sylvain13bdr avatar Aug 20 '26 14:08 Sylvain13bdr

Two additional controls from a Windows/Git Bash repro, in case they help triage. Both point the same way as the MSVCRT/MSYS2 diagnosis in the issue body.

1. PreToolUse hooks are not involved. Worth stating because this environment had a PreToolUse hook that rewrites every Bash command via updatedInput, which is exactly the shape that would explain the bug. Two controls cleared it:

  • A command shape that makes the hook bail (pass through with no updatedInput at all) collapses backslashes identically.
  • Feeding the hook a payload directly returns two backslashes in, two backslashes out.

2. The loss happens inside single quotes, which bash is not permitted to alter. That alone places the corruption before bash parses the line, independent of any shell-level explanation.

Chain measured end to end, reading the emitted command back out of the session transcript:

Stage Backslashes
Emitted by the model (from transcript JSONL) 2
PreToolUse hook, in / out 2 / 2
Received by bash 1

Mitigation that makes it non-silent, which is the worst property of this bug. When a doubled backslash collapses in a generated Python file, Python 3.12 emits a SyntaxWarning and runs the mangled script anyway with exit 0, so a corrupted file is written and looks fine. Setting

PYTHONWARNINGS=error::SyntaxWarning

turns the same input into a hard SyntaxError with exit 1 and nothing written. Python 3.14 does this by default. It does not fix the corruption, but it converts a silent wrong-output failure into a loud one, which was the difference between catching this in seconds and not catching it at all.

Separately, authoring file content with the Write tool rather than through a heredoc avoids the class entirely, since Write takes a path and bytes with no shell parsing between.

emel-purely avatar Aug 28 '26 06:08 emel-purely

@emel-purely — the end-to-end chain you measured (2 at emission, 2/2 through the hook, 1 at bash) matches what I measured on my environment on 2026-08-20, and ruling out PreToolUse hooks is a useful control to have on record.

One correction on the PYTHONWARNINGS note, measured today on Python 3.14.3 (Windows 11, same box as my earlier comment):

Python 3.14 does this by default.

It does not. An invalid escape sequence — the post-collapse state of a doubled backslash — is still a plain SyntaxWarning by default on 3.14.3: the script runs anyway and exits 0, so the corrupted output is still written silently. The warning text itself says these sequences "will not work in the future", i.e. not yet:

$ python probe.py
probe.py:15: SyntaxWarning: "\d" is an invalid escape sequence. Such
sequences will not work in the future. Did you mean "\\d"? A raw string is
also an option.
FICHIER_ECRIT                # exit 0 — mangled bytes written, no error

$ PYTHONWARNINGS=error::SyntaxWarning python probe.py
SyntaxError: "\d" is an invalid escape sequence. Did you mean "\\d"? A raw
string is also an option.    # exit 1 — nothing runs, nothing written

(Verified with a file-writing probe: in the default case the mangled output file is really on disk afterwards; with the filter it is absent. A control script with a correctly doubled escape passes silently in both modes, so the filter discriminates rather than breaking everything.)

So the mitigation is real and worth having, but it has to be opted into on 3.14 as well.

One scoping caution: error::SyntaxWarning filters the whole process, so setting it machine-wide turns an invalid escape inside any third-party library into an import-time failure. Safer to set it per harness/launcher process than in the user environment — and a PreToolUse deny on \\ runs in Bash commands (discussed above) still catches the class one step earlier, before any file is written.

Sylvain13bdr avatar Aug 30 '26 05:08 Sylvain13bdr

Still present on the current desktop build, plus one finding that bears on mitigation design.

Environment (2026-09-05): Windows 11 Home 10.0.26200; Claude desktop app 1.44121.2.0 running Claude Code 2.1.258; standalone CLI 2.1.251 reproduces identically; Git for Windows bash 5.3.15(1)-release (MSYS2 runtime). Repro A from the issue body prints a\b unchanged from what was reported for 2.1.222.

Confirming the mechanism from the harness side. From inside a Bash tool call I read this bash process's own raw Windows command line (cat /proc/$$/winpid, then Win32_Process.CommandLine for that pid). It is one bash.exe -c "..." string: a shell-snapshot preamble, then eval '<command>' with the command's " escaped as \" and its ' as '"'"'. So the harness relies on the MSYS2 un-escaping pass for its own quoting, and that same pass halves the user's \\. Consistent with the body's diagnosis and with the MSYS=noglob result already noted here (I re-measured it: \\ survives, \" handling stops, the wrapper dies with unexpected EOF while looking for matching '"'). A script file passed to bash.exe is untouched.

The user-side mitigation is blocked by a hook contract detail. The natural workaround is a PreToolUse hook that doubles backslashes in tool_input.command via updatedInput, so the transport delivers the command as written. But per the hooks reference, updatedInput takes effect only together with permissionDecision: "allow" — and this build's strings confirm it ("Hook satisfied user interaction ... via updatedInput ..., bypassing permission prompt"). So a rewriting hook necessarily auto-approves the call. That is fine in a bypassPermissions session and unacceptable in any other mode, where it would remove the permission prompt from every Bash command containing \\. Measured today with such a hook gated on permission_mode == "bypassPermissions", in two fresh headless sessions (claude -p --dangerously-skip-permissions, CLI 2.1.251): with the hook, Repro A prints a\\b; with the hook disabled, a\b. So the rewrite works and is exact — it is only the permission coupling that keeps it from being a general user-side fix.

Two possible resolutions from the maintainers' side, either of which would close this class:

  1. Fix the encoding (double backslashes as well as quotes when building the -c string), or pass the script via a temp file / stdin, which the script-file control shows is untouched.
  2. Failing that, let updatedInput apply with permissionDecision: "ask" (prompt shows the rewritten input) so users can ship a safe local fix without granting allow.

Same defect, for cross-reference: #88561, #89392, #90630, and #88578 (hook commands).

david-yuh avatar Sep 05 '26 19:09 david-yuh

Still present on 2.1.282 (Windows 11 Home 10.0.26200, Claude desktop app, Code tab, Git Bash).

printf '%s\n' 'single-quoted: a\\b'
cat <<'EOF'
quoted heredoc: a\\b
EOF

prints a\b twice. The same text written with the Write tool and printed with cat keeps both backslashes, so each pair is halved before bash reads the command. In practice it silently changed a sed regex ([/\\] arrived as [/\]) and Windows paths inside string literals. The workaround here is to put any text with a backslash pair in a file written by the Write tool.

VacationSanta avatar Sep 30 '26 02:09 VacationSanta

Two more reports of this bug aren't linked here yet:

  • #93915 shows the same argv transport also truncates long commands. bash.exe -c cuts off at 8,203 characters, and the result surfaces as a bogus "unexpected EOF" syntax error. Its author found that the truncation and the backslash halving both disappear when the identical command goes to bash on stdin (bash -s), byte-identical up to 259 KB. That supports the stdin option suggested above: one change fixes both bugs.
  • #97409, filed 2026-09-26 against 2.1.281, is a fresh duplicate.

Until there's a fix, a PreToolUse hook that refuses works as a guard. Ours denies any Bash command on Windows that contains two backslashes in a row. A single backslash survives the transport, so it passes. The deny reason tells the model what to do instead: write the text to a file with the Write tool and run it by path, use the PowerShell tool, or use forward slashes in paths. Doubling the backslashes in the hook would give the right bytes, but it runs into the updatedInput limitation described above, so a deny is the simpler option. It ships on by default in token-goat if anyone wants a working copy.

Zelys-DFKH avatar Oct 01 '26 06:10 Zelys-DFKH

I've built a hook-based plugin(io-guard) that checks each call before and after it runs. It got much worse with release of Opus 5.5 and i've noticed the agent often circling or solving non-existing issues due to bad edits. It fixes what it safely can on the fly, moves long heredoc and python -c bodies into a file so the Bash tool can't cut them or halve their backslashes, and rejects the rest with a structured error that names the fix. It also contains a local mcp server with a few file tools, such as atomic writes, several edits to one file in one call and more

Riztazz avatar Oct 01 '26 06:10 Riztazz

For triage: the same halving is also reported in #92543, #93618, #98622 (2.1.285) and #98733 (2.1.286), which are not linked from this thread yet. Still present here on 2.1.284 in the desktop app (Windows 11, Git for Windows 2.55.0, MSYS2 runtime 3.6.9).

tldah4558-prog avatar Oct 02 '26 03:10 tldah4558-prog

Thanks for the root-cause write-up; it saved us a lot of digging. Three things that may help triage, measured today (2026-10-08):

1. Still present on 2.1.294, which is the newest entry in the changelog; no entry from 2.1.286 to 2.1.294 mentions it. Environment: Windows 11 Pro 10.0.26300, Git for Windows 2.56.0.windows.2 (bash 5.3.15, MSYS runtime 3.6.10), Claude Code 2.1.294 (entrypoint claude-desktop).

  • In the Bash tool, printf 'two:[%s] four:[%s]\n' 'a\\b' 'a\\\\b' prints two:[a\b] four:[a\\b]. Inside the same command, $BASH_EXECUTION_STRING already holds a\b and a\\b (one and two backslashes) inside the eval '...' wrapper, while the single backslash in \n arrives intact, so each pair is halved before bash parses anything.
  • Outside Claude Code, Node 24.19.0 spawnSync of bash.exe with positional arguments: a\\b arrives intact, a\\b c arrives as a\b c, q\\x y arrives as q\x y. A pair is halved only in an argument that holds a space, i.e. one Node wraps in quotes.

2. The truncation in #85111 is the same transport, and the two threads do not link each other yet. In the same standalone test, one 10,000-character argument reaches a Node child whole, but reaches bash.exe as 8,186 characters, and MSYS printf.exe prints 8,186 of it, both with exit 0; two 5,000-character arguments arrive whole. So the cut is per argument, and the Bash tool puts the whole wrapped command in one argument. That matches the 8,186 measured in #85111. Further reports of one or both symptoms not linked from here yet: #97692, #99410, #100063.

3. No setting seems to avoid it. Per the environment-variables page (read today), CLAUDE_CODE_SHELL and CLAUDE_CODE_GIT_BASH_PATH only choose which bash binary runs; the command still travels as one -c argument. (Documentation reading; we did not test each variable.)

Suggestion, for whatever it is worth: delivering the command to Git Bash without the MSYS command-line parser, for example on stdin or in a temporary script file passed by path, would end both symptoms at once. Happy to run a test build or a specific probe on this setup if that would help.

HetCreep avatar Oct 08 '26 16:10 HetCreep

Still reproduces on 2.1.295 (Claude desktop app, Code tab), Windows 11 Pro 10.0.26300, Git for Windows 2.53.0.windows.2, GNU bash 5.2.37.

Minimal repro in the Bash tool: printf '%s\n' 'a\\b' prints a\b instead of a\\b. The session transcript (.jsonl) shows the tool input still holds both backslashes, so they are lost between the tool and bash. Same in a quoted heredoc (<<'EOF'). Only runs of two or more are affected (3 → 2, 4 → 2; inside double quotes bash then halves again, 4 → 1). A single backslash, \$, \", a backslash before a backtick and a trailing backslash pass intact. The PowerShell and Write tools are not affected.

Workaround in use here: a PreToolUse hook (matcher Bash) that denies any command containing two consecutive backslashes. Replayed over ~15,000 past Bash commands, it would have denied 1.8% of them, and those commands produced 40 of the 46 Python "invalid escape sequence" warnings in our transcripts.

L0fann avatar Oct 12 '26 05:10 L0fann

Another repro: Windows 11 Pro 10.0.26200, Claude Code desktop app (Code tab), Bash tool via Git Bash. Hit on 2026-09-30, 2026-10-07 and 2026-10-12.

Single quotes don't protect it:

printf '%s\n' 'Q\\s' | od -c

prints Q \ s (expected Q \ \ s).

A quoted heredoc gives the same result:

cat <<'EOF' > out.txt
A\\s B\s C:\\Users
EOF

lands on disk as A\s B\s C:\Users. A lone \s is left alone; only doubled backslashes are halved.

Control, PowerShell tool in the same session:

[System.Text.Encoding]::ASCII.GetBytes('P\\s') -join ','

prints 80,92,92,115, so both backslashes leave the model and the loss is on the Bash tool's path to bash.exe. No PreToolUse hook rewrote these commands.

Workaround: write scripts with the Write tool and run the file, or use the PowerShell tool.

apalm8 avatar Oct 12 '26 22:10 apalm8

Thank you all for the detailed reproductions in this thread. They make the cause very clear.

We built Check (npx @golproductions/check) to address exactly this. It is a PreToolUse hook that reads node -e and python -c code as Git Bash will actually deliver it. If halving has broken the code, Check blocks the command before it runs and instructs Claude to write the script to a file and execute that instead. The broken code never runs, and Claude corrects course on its own.

In the interest of transparency: Check currently catches code that no longer parses after halving. It does not yet catch sed, grep or printf patterns, or the silent "a\\nb" case. A 14-day free trial is available.

For anyone who prefers not to install anything, the workaround remains reliable: have Claude write the script with the Write tool and run the file. Write preserves every backslash.

golproductions avatar Oct 13 '26 09:10 golproductions

Still present on 2.1.300 (latest). Windows 11 Enterprise 10.0.26200, Claude Code CLI 2.1.300, Git for Windows 2.55.0.windows.3, GNU bash 5.3.15(1)-release, MSYS 3.6.9.

Bash tool command:

printf '%s\n' 'A:\\' 'B:\\\\' 'D:\\"x' 'E:\\$x' 'H:a\\\b' | od -c

Expected (single quotes are literal): A:\\ B:\\\\ D:\\"x E:\\$x H:a\\\b Actual: A:\ B:\\ D:\\"x E:\$x H:a\\b. Each run of n backslashes not directly followed by " arrives as ceil(n/2). A quoted heredoc (<<'EOF') behaves the same.

One point not yet in this thread: Claude Code already ships a transport that is immune. The PowerShell tool starts pwsh -Command "$__claudeCodeScript = $env:CLAUDE_CODE_SHELL_LAUNCHER_SCRIPT; … Invoke-Expression", so its script never crosses the Windows command line. In the same session, 'A:\\','B:\\\\','H:a\\\b' printed exactly as written, and scripts of 20,668 characters ran intact. Handing the Git Bash wrapper over the same way (an environment variable plus bash -c 'eval "$VAR"', or stdin or a temp file) would fix this issue and the 8,186-character cut in #85111 together.

For scale, one machine over about 7 weeks: 85,766 recorded tool calls, with 92 failures (79 incidents in 75 separate agent contexts) attributable to the halving. That is a lower bound, because the silent cases leave no error behind.

4cio avatar Oct 15 '26 18:10 4cio

Still present on 2.1.309 (today's latest; stable 2.1.308 too), with output identical to 2.1.280. Windows 11 Pro 10.0.26200, Git for Windows 2.50.0, bash 5.2.37, MSYS runtime 3.6.3. The thread stops at 2.1.300.

Bash tool commands and what they printed, same on 2.1.280 and 2.1.309:

printf '%s|' 'a\\q'      a\q|
printf '%s|' 'a\\\\q'    a\\q|
printf '%s|' 'a\\\\\q'   a\\\q|
printf '%s|' 'a\\"q'     a\\"q|
printf '%s|' 'a\\'       a\|

Across 14 contexts (single and double quotes, unquoted, quoted and unquoted heredoc, $'...', before a space, a newline, a closing quote, the end of the command) at runs of 1 to 6, the result depends only on the character after the run: a " keeps the run intact, anything else halves it to ceil(n/2). The wrapper appends a ' after the command, so a run at the very end halves as well. One silent case not mentioned yet: an unquoted pair before a newline becomes a line continuation, so printf '%s|' a\\ followed by echo next prints aecho|next|.

What this did to real commands: print('a\\b'.replace('\\', '/')) in a quoted heredoc fails with SyntaxError: unterminated string literal, and sed 's#\\#/#g' fails with unterminated `s' command.

On the rewrite workaround: updatedInput returned with no permissionDecision at all is applied (measured on 2.1.280, 2.1.308 and 2.1.309 under an allow rule, and on 2.1.280 under bypassPermissions), so a rewriting hook does not have to grant allow; the hooks reference says permission rules are evaluated against the returned input. Double only the runs not followed by ", since those arrive intact and would come out doubled: that delivered the written command exactly in 94 of 94 cases on 2.1.280 and on 2.1.309. Mapping even n to 2n and odd n to 2n-1 does the same while keeping the escape parity the permission parser reads.

Not linked from here yet: anthropics/claude-code#100936, anthropics/claude-code#102533, anthropics/claude-code#103496.

The full matrix, with the raw Windows command lines captured on both releases, is available if useful.

alex-feel avatar Oct 23 '26 06:10 alex-feel

Also reproduced on an older runtime: Windows 10 Pro 10.0.19043, Git for Windows 2.35.1 (MSYS 3.3.3, bash 4.4.23), Claude Code 2.1.293 in the desktop app's Code tab. The reports above are all on MSYS 3.6.x, so this is not tied to a recent runtime.

printf '%s\n' 'printf: c\\d' prints c\d. The session .jsonl records the tool input with both backslashes.

How often it silently alters text. I swept 600 session transcripts (23,409 Bash tool calls). 145 heredoc commands had a doubled backslash in the heredoc body, so each of them reached bash altered. Most were python - <<'EOF' edit scripts and cat > file <<'EOF' writes, which means the altered text landed in files:

  • \\b in a Python regex became a 0x08 BACKSPACE byte in a .ps1, which silently removed a word boundary from the regex;
  • \\n / \\t in string literals became real newlines and tabs, which broke string literals;
  • \\x00 became real NUL bytes, which turned a markdown file binary in git;
  • exact-string replaces matched nothing.

Nothing fails at the moment it happens. The damage surfaces later, in a test or a diff.

One caution for anyone writing a guard. We measured the 38 recorded commands that had \\ inside a single-quoted argument (grep / awk / sed patterns). Most of them depended on the halving: the agent wrote \\b and got the \b it meant. A fix to the transport will change what those commands do, so agents and prompts tuned around the bug will need re-checking once it ships. Our PreToolUse guard therefore refuses \\ only inside heredoc bodies, where the text is always meant literally, and leaves arguments alone.

TeleBrady avatar Oct 23 '26 19:10 TeleBrady

Measurements for the fix proposed in this thread: hand the command to bash through the environment instead of the command line, as the PowerShell tool already does with CLAUDE_CODE_SHELL_LAUNCHER_SCRIPT (see also #102533, #85111, #93618, #93915).

Claude Code 2.1.308 (desktop app 3.6556.2.0), Windows 10 (19045), Git for Windows 2.55.0.windows.3 (bash 5.3.15, MSYS runtime 3.6.9).

Where the damage happens. bash.exe is an MSYS program started by a non-MSYS parent, so the runtime rebuilds its arguments from the Windows command line with its own rules, and every quoted word goes through the runtime's glob step (build_argv and globify in winsup/cygwin/dcrt0.cc). That step halves backslash runs and cuts a word at 8,186 characters, without an error. No Claude Code is needed to see it; from PowerShell:

$e = 'C:\Program Files\Git\usr\bin\echo.exe'
(& $e ('e ' * 5000)).Length    # 8186, not 10000
& $e 'a\\b c'                  # prints: a\b c

MSYS=noglob removes both, but it is no fix for the Bash tool: a double quote inside a quoted argument is then mangled (say "hi" there arrives as say \hi\ there), and Claude Code writes \" for every embedded double quote.

What the environment route gives. I reproduced the tool's launch line outside Claude Code (same quoting and wrapper text) with 142 payloads (backslash runs, quotes, non-ASCII, control characters, lengths up to 33,000), each sent as printf '%s' '<payload>' and as a quoted heredoc, and compared the bytes that arrive:

route byte-exact
bash.exe -c "<wrapper and command>" (today) 123 of 142
bash.exe -c '__s=$V; unset V; eval "$__s"' with the wrapper in V 137 of 142

Today's 19 misses: 12 halved backslash runs, the 8,000- and 8,300-character commands (unexpected EOF), 3 payloads holding CR, a lone surrogate and a 33,000-character command. The environment route fixes the halving and both length cases. The 5 that remain are not transport faults: bash's own parser drops CR on every route, a lone surrogate cannot be encoded, and 33,000 characters exceed the 32,767-character command line of the stand-in launcher I used (a built-in route would have the environment-variable limit instead; a 40,160-character variable arrived whole in a direct test). Start-up is 32 ms against 31 ms for plain bash.exe -c true (medians).

The cut is not always loud. A bash.exe -c script of 8,284 characters holding a quoted heredoc with an 8,256-character body exits 0 with 8,173 body bytes, and the echo after the heredoc never runs; the only sign is bash's stderr warning here-document at line 1 delimited by end-of-file. The same text through the environment arrives whole.

The same route would suit shell-form hooks and the snapshot creation (-c -l). Stdin (bash -s) also fixes the Bash tool, whose wrapper already redirects the command's stdin from /dev/null, but not hooks, whose stdin carries the hook input.

jullduxster avatar Oct 25 '26 21:10 jullduxster

Still present on 2.1.310. I measured it across my own sessions: 37,654 Bash calls, 1,222 with a doubled backslash, ~260 real failures, 108 of which left a broken .py on disk. Today it corrupted a PreToolUse guard hook with onFailure: block, which locked every Claude Code session on the machine until I fixed it by hand in Notepad.

This issue has been open for 2.5 months, the root cause and a fix were diagnosed by users in this very thread, and there is still not a single reply from Anthropic. Users are now shipping their own hooks to work around a bug in your transport layer. Please fix it or at least acknowledge it.

tichondrius808 avatar Oct 26 '26 15:10 tichondrius808

Still present on 2.1.312 (CLI, 2026-10-28). Windows 11 Pro 10.0.26200, Git for Windows 2.56.0.windows.3, bash 5.3.15(2), MSYS runtime 3.6.10.

echo 'x\\y' | od -c                 ->  x \ y        (expected x \ \ y)
cat <<'EOF' | od -c  /  a\\b  / EOF ->  a \ b        (expected a \ \ b)
printf '%s|' 'A\\\B'                ->  A\\B|        (expected A\\\B|)
echo 'A\B' 'G\nH' | od -c           ->  unchanged    (single backslashes)

The same two lines written to a file with the Write tool and run as bash file.sh print x \ \ y and a \ \ b.

Two controls not in the thread yet:

  1. CLAUDE_CODE_SHELL_PREFIX is not involved. Two claude -p --model haiku --allowedTools Bash --setting-sources local runs of the same prompt, one with the prefix set to a pass-through wrapper script and one with it unset (env -u). A PreToolUse hook logged tool_input.command each run: both backslashes present in all four calls, and bash printed x \ y and a \ b in both runs. So the halving sits after the hooks and does not depend on the prefix.

  2. Frequency, one machine, 7 days (2026-10-21 to 2026-10-27): 61,610 Bash tool calls, 947 holding a \\ (1.5%), 752 of them in a context where halving changes what runs (quoted heredocs into Python, sed and grep patterns, unquoted Windows paths). The rest were pairs inside double quotes, where bash would have halved them anyway.

Mitigation in use here, for anyone who finds a deny hook too blunt: a PreToolUse hook that lets the command run and returns only additionalContext with one line saying the Bash tool halves \\ here and to send the text through the Write tool. The model acts on it, and nothing is blocked.

CharlesHe16 avatar Oct 28 '26 15:10 CharlesHe16

Also ran into this and filed a bug report here. Later discovered the likely root cause, here.

ByteJuggler avatar Nov 06 '26 14:11 ByteJuggler