cd wslpath as bash function shell 引用问题
当使用 wsl(Linux 的 Windows 子系统)时,我经常想将目录更改为 Windows 目录。 wslpath 采用 Windows 目录(如 C:\Windows)并将其转换为 wsl 版本 /mnt/c/Windows。通过引用这样的构造效果很好(尽管我怀疑存在边缘情况):
cd "`wslpath 'C:\Windows'`"
我想要做的是将其转换为 bash 函数,我可以将其放入我的 .bashrc 文件中,以使其更容易键入。我希望能够输入类似以下内容:
wcd 'C:\Windows'
问题是引用所有这些引号,以便我得到我想要的内容。这个选项失败了:
wcd ()
{
cd "`wslpath '$1'`"
}
那个永远不会起作用,但我更有希望:
wcd ()
{
cd \"\`wslpath \'$1\'\`\"
}
这就是我对 shell 引用的限制,但我确信应该可以让它正常工作。
When using wsl (windows subsystem for linux) I often want to change directory to a windows directory. wslpath takes a windows directory like C:\Windows and converts it to the wsl version /mnt/c/Windows. With a bit of quoting a construct like this works well (although I suspect there are edge cases):
cd "`wslpath 'C:\Windows'`"
What I want to do is convert this into a bash function that I can put into my .bashrc file to make it a bit easier to type. I want to be able to type something like:
wcd 'C:\Windows'
The problem is quoting all these quotes so I get what I want. This option fails:
wcd ()
{
cd "`wslpath '$1'`"
}
That one was never going to work but I was more hopeful about:
wcd ()
{
cd \"\`wslpath \'$1\'\`\"
}
That's about my limit with shell quoting but I'm sure it should be possible to get this to work properly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

单引号防止变量扩展,因此
'$1'
生成文字字符串$1
。命令替换是命令边界,因此您可以说,
而不会遇到公认的第二个引号关闭由第一个左引号开始的字符串,而不是嵌套,否则您通常无法做到这一点。
...虽然很大程度上首选现代命令替换语法绝对应该在任何新代码中使用;
感谢您正确引用您的论点!
The single quotes prevent variable expansion, so
'$1'
produces the literal string$1
.The command substitution is a command boundary, so you can say
without bumping into what admittedly can look like the second quote closing the string started by the first opening quote, instead of nesting, which you otherwise generally cannot do.
... Though the vastly preferred modern command substitution syntax should definitely be used in any new code instead;
Kudos for taking care to quote your arguments properly!