Windows 上的 Git Bash 会误解转义序列

问题描述 投票:0回答:1

我正在编写一个执行 bash 命令的跨平台 Nodejs 脚本。它在 Linux/MacOS/Windows 上应该以相同的方式工作,但在我使用 Git Bash 的 Windows 机器上,转义序列似乎存在问题。

在尝试 child_process.spawn 函数时,我遇到了一个奇怪的行为,我能够在 Windows cmd.exe 中重现该行为:

d:\>bash -c "echo $'this is \a test'"
this is  test

d:\>bash -c "echo $'this is \\a test'"
this is  test

第一个输出是预期的,但在第二个输出中,看起来

\\a
被视为
\a
转义序列。

在交互式 bash 会话中运行相同的命令会产生正确的结果:

$ echo $'this is \a test'
this is  test

$ echo $'this is \\a test'
this is \a test
node.js windows bash cmd git-bash
1个回答
0
投票

您正在使用双引号字符串调用

bash -c
,因此您调用
bash -c
的 shell 在将结果字符串传递给
bash -c
之前会解释其中的转义序列,因此您需要添加又一层转义,这样当
bash -c
看到它时,转义仍然是本身转义:

$ bash -c "echo $'this is \a test'"
this is  test

$ bash -c "echo $'this is \\a test'"
this is  test

$ bash -c "echo $'this is \\\a test'"
this is \a test

您应该使用单引号,例如:

$ bash -c $'echo "this is \a test"'
this is  test

$ bash -c $'echo "this is \\a test"'
this is \a test
© www.soinside.com 2019 - 2024. All rights reserved.