How to reliably write files containing multi-byte Unicode (emoji, special symbols) when write_file fails with 'unknown error' by falling back to run_shell with
复制下面这句话,粘贴给 Claude Code、Codex、Cursor 等 AI 编程工具,它会读取安装说明并在你确认后完成安装。
请阅读 https://ai.atlankj.com/install/asset/gh-unicode-safe-file-writing-ac99e12f4f71 ,按照其中的说明把「unicode-safe-file-writing」安装到你(当前 AI 工具)中。执行前先告诉我将运行的命令和写入的位置,等我确认。
查看 AI 将读取的安装说明正在读取 GitHub 原文…
内容来自 GitHub 原始文件,由原作者维护。在 GitHub 查看
The write_file tool may fail with 'unknown error' when the file content
contains multi-byte Unicode characters such as:
🚀, ✅, ❌)→, •, —, ©)This is a known encoding limitation of write_file.
Fall back to run_shell and write the file using a shell heredoc
(cat > file << 'EOF' ... EOF). The single-quoted delimiter 'EOF'
prevents the shell from interpreting any special characters inside the
block.
If write_file returns an error such as:
Error: unknown error
and the content contains non-ASCII characters, assume a Unicode encoding issue and proceed to the heredoc fallback.
Before embedding content in the heredoc, decide whether to:
Common replacements:
| Original | Replacement |
|---|---|
✅ | [OK] |
❌ | [ERROR] |
🚀 | [START] |
→ | -> |
• | - |
— | -- |
Use run_shell with the following pattern:
cat > path/to/file.ext << 'EOF'
...file content here (with Unicode stripped/replaced if needed)...
EOF
Key details:
'EOF' (single-quoted) as the heredoc delimiter — this disables all
shell variable expansion and special character interpretation inside the block.EOF (it must start at column 0).'HEREDOC_END', 'FILEEND').write_file(
path="src/components/StatusPanel.ts",
content="// Status icons\nconst icons = { ok: '✅', err: '❌', run: '🚀' };\n"
)
# → Error: unknown error
cat > src/components/StatusPanel.ts << 'EOF'
// Status icons
const icons = { ok: '[OK]', err: '[ERROR]', run: '[START]' };
EOF
Or, if UTF-8 output is acceptable in the environment:
cat > src/components/StatusPanel.ts << 'EOF'
// Status icons
const icons = { ok: '✅', err: '❌', run: '🚀' };
EOF
When writing several files and one fails, write the others with write_file
as normal and apply the heredoc fallback only to the failing file(s):
# Write multiple files that contain Unicode
cat > src/utils/icons.ts << 'EOF'
export const ICONS = {
success: '[OK]',
failure: '[FAIL]',
pending: '[...]',
};
EOF
cat > src/utils/labels.ts << 'EOF'
export const LABELS = {
title: 'Dashboard',
subtitle: 'Real-time status',
};
EOF
write_file first — only fall back to the heredoc
approach when write_file fails.run_shell with cat path/to/file or
head -5 path/to/file to confirm the content was written correctly.write_file auto-creates parent directories;
the heredoc approach does not. Pre-create directories with
mkdir -p path/to/dir if needed.