Fish:有条件地自动加载函数子集

Fish: Conditionally autoload subset of functions

我正在测试 fish shell,我正在寻找一种方法来实现我之前使用 .bash_profile 所做的事情。我使用 switch 语句来区分主机名,允许我有 1 centralized/synced .bash_profile,它包含一组单独的别名和函数,用于它工作的每台机器(例如工作相关我的工作计算机上的东西,以及我个人计算机上的个人副项目相关的东西)。

我知道 ~/.config/fish/functions 中的自动加载函数 fish 等同于 .bash_profilebash 中的无条件定义函数。但是有没有一种方法可以指定仅自动加载这些函数的一个子集?

谢谢!

Fish 在变量 fish_function_path 中的目录中搜索自动加载的函数,并加载它找到的第一个函数。在我的系统上,这默认为

$fish_function_path: set in global scope, unexported, with 4 elements
$fish_function_path[1]: length=36 value=|/Users/krader/.config/fish/functions|
$fish_function_path[2]: length=29 value=|/usr/local/etc/fish/functions|
$fish_function_path[3]: length=40 value=|/usr/local/share/fish/vendor_functions.d|
$fish_function_path[4]: length=31 value=|/usr/local/share/fish/functions|

所以我要做的是在名称中包含主机名的目录前面添加一个目录,并将所有机器特定的功能放在该目录中。并继续将通用的、非机器特定的函数放在 ~/.config/fish/functions.

我做同样的事情:我的 ~/.config/fish/config.fish 包含

set host_config ~/.config/fish/config.(hostname).fish
test -r $host_config; and source $host_config
set -e host_config

然后是 config.(hostname).fish 包含我对该机器的函数和变量设置。

您必须注意的一件事是记住您想要funced/funcsave某些功能。

Krutis Rader's $fish_function_path知识的启发,我在~/.config/fish/functions做了如下文件夹结构:

$ tree -FC ~/.config/fish/functions/
├── PersonalComputer1/
│   └── PersonalComputer1_only_function.fish
├── PersonalComputer2/
│   └── PersonalComputer2_only_function.fish
├── WorkComputer1/
│   └── WorkComputer1_only_function.fish
├── WorkComputer2/
│   └── WorkComputer2_only_function.fish
├── personal/
│   └── personal_only_function.fish
├── work/
│   └── work_only_function.fish
└── common_function.fish

然后我通过将此添加到我的 ~/.config/fish/config.fish 来设置我的 $fish_function_path:

# Set up work/personal autoload function path
switch (hostname) WorkComputer1 WorkComputer2
    set -gx fish_function_path "/Users/USERNAME/.config/fish/functions/work" $fish_function_path

case PersonalComputer1 PersonalComputer2
    set -gx fish_function_path "/Users/USERNAME/.config/fish/functions/personal" $fish_function_path

end

# Set up host-specific autoload function path
set -gx fish_function_path "/Users/USERNAME/.config/fish/functions/"(hostname) $fish_function_path

导致 $fish_function_path 看起来像:

/Users/USERNAME/.config/fish/functions/WorkComputer1
/Users/USERNAME/.config/fish/functions/work
/Users/USERNAME/.config/fish/functions
/usr/local/Cellar/fish/2.7.1/etc/fish/functions
/usr/local/share/fish/vendor_functions.d
/usr/local/Cellar/fish/2.7.1/share/fish/functions