进入目录后执行 bash 函数
我想在进入新目录时执行特定的 bash 函数。有些人认为:
alias cd="cd $@ && myfunction"
$@
在那里不起作用,并且添加反斜杠也没有帮助。我也有点担心弄乱 cd,如果这适用于其他更改目录的命令,例如 pushd
和 popd
,那就太好了。
有更好的别名/命令吗?
I'd like to execute a particular bash function when I enter a new directory. Somethink like:
alias cd="cd $@ && myfunction"
$@
doesn't work there, and adding a backslash doesn't help. I'm also a little worried about messing with cd, and it would be nice if this worked for other commands which changed directory, like pushd
and popd
.
Any better aliases/commands?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
别名不接受参数。你应该使用一个函数。无需在每次发出提示时自动执行它。
builtin
关键字允许您重新定义 Bash 内置函数,而无需创建递归。引用该参数可以使其在目录名称中有空格的情况下起作用。Bash 文档 说:
Aliases don't accept parameters. You should use a function. There's no need to execute it automatically every time a prompt is issued.
The
builtin
keyword allows you to redefine a Bash builtin without creating a recursion. Quoting the parameter makes it work in case there are spaces in directory names.The Bash docs say:
我能想到的最简单的解决方案就是这个
,应该可以做到。它将适用于所有命令,并将在显示提示之前触发。
The easiest solution I can come up with is this
That ought to do it. It'll work with all commands, and will get triggered before the prompt is displayed.
还有一些其他版本,包括
这两个都支持 bash 和 zsh
There are a few other versions of this out there, including
Both of these support both bash and zsh
我编写了一个 ZSH 脚本,利用回调函数 chpwd 来获取项目特定的 ZSH 配置。我不确定它是否适用于 Bash,但我认为值得一试。如果它在您要进入的目录中找不到脚本文件,它将检查父目录,直到找到要获取的脚本(或直到到达
/
)。当 cd'ing 出目录时,它还会调用一个函数unmagic
,这允许您在离开项目时清理环境。http://github.com/jkramer/home/blob/master /.zsh/func/magic
“magic”脚本示例:
I've written a ZSH script utilizing the callback function
chpwd
to source project specific ZSH configurations. I'm not sure if it works with Bash, but I think it'll be worth a try. If it doesn't find a script file in the directory you're cd'ing into, it'll check the parent directories until it finds a script to source (or until it reaches/
). It also calls a functionunmagic
when cd'ing out of the directory, which allows you to clean up your environment when leaving a project.http://github.com/jkramer/home/blob/master/.zsh/func/magic
Example for a "magic" script: