我有几个实用程序命令和别名,它们在任何目录中都足够通用,可以满足我自己的要求。但是有某些目录,例如“build”,我需要自定义行为。
为此,我在这些目录中创建了一个不同的文件,其中包含具有相同名称的函数和别名的修改(这样我就不需要记住新名称)。
目前,我在 cd'ing 到特定目录后手动获取文件
source custom_aliases_n_fns
Run Code Online (Sandbox Code Playgroud)
这运作良好,但我希望自动执行此文件来源。
有没有办法将 cd'ing 上的文件源到特定目录?
注意:我采用了这种方法,因为我不想更改系统范围的用户别名。
在 中zsh,您可以使用chpwd特殊的钩子函数,只要当前工作目录发生更改,就会调用该函数:
custom_aliases_n_fns_already_sourced=false
chpwd() {
if
! $custom_aliases_n_fns_already_sourced &&
[[ $PWD = /some/dir && -f custom_aliases_n_fns ]]
then
source ./custom_aliases_n_fns
custom_aliases_n_fns_already_sourced=true
fi
}
Run Code Online (Sandbox Code Playgroud)
我不建议盲目地在任何目录中获取文件(因此检查$PWD = /some/dir),因为这可能会被滥用。
除了更改唯一的chpwd钩子之外,您还可以执行以下操作:
myhook() {
if
[[ $PWD = /some/dir && -f custom_aliases_n_fns ]]
then
source ./custom_aliases_n_fns
chpwd_functions[(Ie)$0]=() # remove ourselves from the array
fi
}
chpwd_functions+=(myhook)
Run Code Online (Sandbox Code Playgroud)
这允许在当前工作目录更改时调用多个钩子函数,这里我们不记录我们是否已经获取该文件,而是在获取chpwd文件后从挂钩列表中删除我们的函数。