Bash:别名中嵌套反引号会导致问题

发布于 2024-12-28 00:45:09 字数 581 浏览 2 评论 0原文

我正在尝试编写一个别名,该别名将跳转到包含指定文件的 cwd 的后代目录(或第一个 find 找到的此类文件名的出现):

以下命令组合可实现所需的结果:

cd `dirname \`find -name 'MyFile.txt' | sed -n 1p\``

但是,我似乎无法以正确的方式转义它来创建工作别名:

alias jump="cd \`dirname \\\`find -name '$1' | sed -n 1p\\\`\`"

输出:

/*
dirname: missing operand
Try `dirname --help' for more information.
bash: cd: find: No such file or directory

我的逻辑是反引号需要在带有单个 \ 的双引号字符串中转义,我可以'要做\\ 被转换为字符串中的单个反斜杠,因此第二个嵌套反引号需要 1+2=3。

有什么建议吗?

I'm trying to write an alias which will jump to the descendant directory of cwd which contains a specified file (or the first find found occurrence of such a filename):

The following command combination achieves the desired result:

cd `dirname \`find -name 'MyFile.txt' | sed -n 1p\``

However, I can't seem to escape this in the correct way to create a working alias:

alias jump="cd \`dirname \\\`find -name '$1' | sed -n 1p\\\`\`"

Output:

/*
dirname: missing operand
Try `dirname --help' for more information.
bash: cd: find: No such file or directory

My logic is that backticks need escaping in a double quoted string with a single \ and I can't do \\ gets translated to a single backslash within a string, so the second nested backtick requires 1+2=3.

Any suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

烦人精 2025-01-04 00:45:09

别名不能接受像 $1 这样的参数。使用函数代替。

还可以使用 $(command) 进行命令替换,而不是使用反引号,因为这样更容易嵌套。

该函数将是:

jump() {
    cd $(dirname $(find -name "$1" | sed -n 1p))
}

An alias cannot take an argument like $1. Use a function instead.

Also use $(command) for command substitution instead of backticks, as it is easier to nest.

The function would be:

jump() {
    cd $(dirname $(find -name "$1" | sed -n 1p))
}
末蓝 2025-01-04 00:45:09

反引号是命令替换的旧形式,你可以'不要轻易地筑巢。但是,新的 $() 表单 确实很容易嵌套:

cd $(dirname $(find -name 'MyFile.txt' | sed -n 1p))

Backticks are the old form of command substitution, and you can't nest them easily. However, the new $() form does nest easily:

cd $(dirname $(find -name 'MyFile.txt' | sed -n 1p))
沧桑㈠ 2025-01-04 00:45:09

Backticks 不提供嵌套。尝试使用命令替换,其语法为$(..)

在您的情况下,它将是

cd $(dirname $(find /path/to/search -name 'MyFile.txt' | sed -n 1p)) 

Backticks doesn't offer nesting. Try using command substitution which has the syntax $(..)

In your case it will be

cd $(dirname $(find /path/to/search -name 'MyFile.txt' | sed -n 1p)) 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文