Resolve file access failures by changing to the correct working directory before command execution
复制下面这句话,粘贴给 Claude Code、Codex、Cursor 等 AI 编程工具,它会读取安装说明并在你确认后完成安装。
请阅读 https://ai.atlankj.com/install/asset/gh-working-directory-resolution-7658e8aaf841 ,按照其中的说明把「working-directory-resolution」安装到你(当前 AI 工具)中。执行前先告诉我将运行的命令和写入的位置,等我确认。
查看 AI 将读取的安装说明正在读取 GitHub 原文…
内容来自 GitHub 原始文件,由原作者维护。在 GitHub 查看
Many file operation failures occur because the tool's current working directory doesn't match where the target files are located. This skill provides a reliable pattern for resolving such issues.
File operations fail with errors like:
These failures often occur even when files are present in the workspace—the working directory context is simply wrong.
Always explicitly set the working directory before file operations by prepending cd to your shell commands.
cd /path/to/target/directory && your-command-here
run_shellrun_shell(command="cd /workspace/project && cat config.json")
cd /workspace/project && ls -la && cat README.md && python script.py
cd /workspace/project 2>/dev/null && cat file.txt || echo "Directory not found"
Use this pattern when:
read_file fails to locate an existing fileexecute_code_sandbox can't find referenced filesUse absolute paths when possible
cd /workspace/project/src && python main.py
Combine related operations to avoid repeated cd calls
cd /workspace/project && ./build.sh && ./test.sh
Verify directory exists before operations
[ -d /workspace/project ] && cd /workspace/project && ls
For scripts, set working directory at the start
#!/bin/bash
cd "$(dirname "$0")" || exit 1
# Rest of script runs from script's directory
| Issue | Wrong Approach | Correct Approach |
|---|---|---|
| Relative paths | cat config.json | cd /workspace && cat config.json |
| Assumed cwd | python script.py | cd /workspace && python script.py |
| Multiple dirs | cd dir1; cd dir2; cmd | cd dir1/dir2 && cmd |
If cd also fails:
pwd to check current directoryfind or ls -R to locate filesls -la /path/to/checkpwd && find /workspace -name "target_file.txt" 2>/dev/null
This pattern is especially valuable when tools like execute_code_sandbox or read_file fail but run_shell with explicit directory context succeeds.