带参数的 Bash 别名失败

发布于 2024-11-16 18:20:29 字数 408 浏览 2 评论 0原文

我运行以下命令来搜索文件中的文本并显示漂亮的输出:

$ grep -rnI "SEARCHTERM" . | sed 's/\:\s\+/\:\n/g'
./path/filename.php:LINENUMBER:
This line contains SEARCHTERM

但是当我尝试将其作为别名运行时,我收到错误:

$ alias lookfor="grep -rnI '\\!^' . | sed 's/\:\s\+/\:\n/g'"
$ lookfor SEARCHTERM
sed: can't read SEARCHTERM: No such file or directory

对于我的别名失败的原因有什么想法吗?我确信这是某种引用问题......

I run the following command to search for text in files and display a pretty output:

$ grep -rnI "SEARCHTERM" . | sed 's/\:\s\+/\:\n/g'
./path/filename.php:LINENUMBER:
This line contains SEARCHTERM

But when I try to run it as an alias I get an error:

$ alias lookfor="grep -rnI '\\!^' . | sed 's/\:\s\+/\:\n/g'"
$ lookfor SEARCHTERM
sed: can't read SEARCHTERM: No such file or directory

Any thoughts as to why my alias is failing? I'm sure it's some sort of quoting issue...

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

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

发布评论

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

评论(2

世界和平 2024-11-23 18:20:29

Bash(令人烦恼的是,恕我直言)不支持别名参数。相反,我建议将您想要的内容写为函数(功能更强大):

lookfor() {
  grep -rnI '\\!^' "$@" | sed 's/\:\s\+/\:\n/g'
}

从长远来看,函数无论如何都更好...它们会让您扩展它以进行错误处理等,如果您愿意的话,稍后再进行扩展。

Bash (annoyingly, IMHO) doesn't support arguments for aliases. Instead, I'd suggest writing what you want as a function instead (which are much more powerful):

lookfor() {
  grep -rnI '\\!^' "$@" | sed 's/\:\s\+/\:\n/g'
}

Functions in the long run are better anyway... They'll let you expand it for error handling, etc, later if you like.

回忆那么伤 2024-11-23 18:20:29

我最终创建了一个 ~/bin 文件夹,并在其中放置了一个名为 lookfor 的可执行文件,其中包含以下内容:

#!/bin/sh
grep -rnI "$1" . | sed 's/\:\s\+/\:\n/g'

~/bin文件夹已被我的发行版确认为在 PATH 中,但对于那些没有自动设置此文件夹的人,您可以通过将以下内容添加到您的 PATH 中:~/.bashrc

if [ -d ~/bin ] ; then
    PATH=~/bin:"${PATH}"
fi

I ended up creating a ~/bin folder, and placing an executable file in there named lookfor, with the following content:

#!/bin/sh
grep -rnI "$1" . | sed 's/\:\s\+/\:\n/g'

The ~/bin folder is already acknowledged by my distro as being in the PATH, but for those who don't have this automatically set, you can add it to your PATH by putting the following in your ~/.bashrc:

if [ -d ~/bin ] ; then
    PATH=~/bin:"${PATH}"
fi
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文