非引号波浪号致 PATH 解析异常:nono 沙箱工具揭示 Shell 变量展开陷阱与修复方案

原标题:Don't Put Tilde In Your Path
38AI 研判分

开发者在使用 nono 智能体沙箱工具时发现,在 `~/.bashrc` 等配置文件中以双引号包裹的 `export PATH="$PATH:~/.local/bin/"` 写法会导致波浪号无法正确展开为家目录路径。文章指出 Bash 仅在特定赋值语境下执行波浪号扩展,建议统一改用 `$HOME` 变量以确保路径解析的稳定性与安全性。

报道正文

I was playing with the nono agent sandboxing tool and it greeted me with a warning: PATH entries the sandbox can write to: ~/.local/bin/ which looked suspicious.

nono warning about PATH entries the sandbox can write to

In other words, doing this in your ~/.bashrc or ~/.zshrc:

BASH
export PATH="$PATH:~/.local/bin/"

If a word begins with an unquoted tilde character (‘~’), all of the characters up to the first unquoted slash (…) are considered a tilde-prefix. (…) Bash checks each variable assignment for unquoted tilde-prefixes immediately following a ‘:’ or the first ‘=’, and performs tilde expansion in these cases. (…)

And to fix this, we can do this:

BASH
export PATH="$PATH:$HOME/.local/bin/"

Note that the unquoted version export PATH=$PATH:~/.local/bin actually works in Bash and Zsh, because tilde expansion is also performed in variable assignments after = and after each :. But relying on that is fragile as for example, a whitespace will break the variable assignment.

The problem can also be seen here:

文本
$ ls -la
total 0
drwxr-xr-x@   2 dc  staff    64 Oct  2 13:37 .
drwxr-x---+ 105 dc  staff  3360 Oct  2 13:37 ..
$ mkdir -p ./~/.local/bin/
$ printf '#include <stdio.h>\nint main() { puts("hello"); }'>a.c; gcc a.c -o ./~/.local/bin/kek
$ PATH="~/.local/bin/" kek
hello
$ tree -f
.
├── ./~
│   └── ./~/.local
│       └── ./~/.local/bin
│           └── ./~/.local/bin/kek
└── ./a.c

4 directories, 2 files

Demo showing that a literal tilde in PATH resolves to a ./~/ directory in the current working directory

As we can see, the kek binary was found and executed from ./~/.local/bin/ — the home directory was never involved.

Check your PATH

You can quickly check whether you have this problem with:

文本
$ echo "$PATH" | grep -- '~'

or, to see each entry on its own line:

文本
$ echo "$PATH" | tr ':' '\n' | grep '~'
~/.local/bin/

If it prints anything, go fix your .bashrc/.zshrc/.profile and replace the ~ with $HOME :).

Btw, kudos to the nono tool for warning about this - even though the warning could be more verbose (PR incoming).