2013-09-26 60 views
0

我有我的.zshrc底部启动.zshrc自动加载bash脚本的功能

[[ -e $HOME/.myapp/myapp.sh ]] && source $HOME/.myapp/myapp.sh 

myapp.sh从文件中装载一些环境变量称为script_properties

{ [[ -e $HOME/.myapp/script_properties ]] && source $HOME/.myapp/script_properties; } || {printf "Please run setup script to set build configuration defaults.\n" && exit; } 

和然后检查一个目录(lt_shell_functions_dir),其中有一些bash脚本需要作为zsh函数加载。我希望能够从命令提示符下执行诸如“ltbuild”之类的操作,它是我想作为函数运行的bash脚本的名称。当我从zsh命令提示符运行“autoload ltbuild”时,它将该文件作为函数加载(因为它位于我的fpath中),并且可以运行它。当我尝试从启动时执行的脚本中加载它时,我不必键入“autoload ltbuild”,它不起作用。我感谢帮助!

if [[ -d $lt_shell_functions_dir ]]; then 
    fpath=($lt_shell_functions_dir $fpath) 
    for function_file in $lt_shell_functions_dir/* 
    do 
    autoload $function_file || printf "Autoloading $function_file failed\n"   
    done 
    unset function_file 
else 
    printf "no $lt_shell_functions_dir exists.\n" 
fi 

例子:

我有一个名为echome已经在它的文件:

echo "I'm a file running as a function" 

当我开始一个shell:

[[email protected][ 3:06PM]:carl] echome 
zsh: command not found: echome 
[[email protected][ 3:06PM]:carl] autoload echome 
[[email protected][ 3:07PM]:carl] echome 
I'm a file running as a function 

回答

0

应注意:我不知道为什么这不是printin g“自动加载失败”,即使在仔细阅读man zshbuiltins之后。幸运的是,zsh有一个很好的社区,如果你被困住了(包括邮件列表和IRC) - 他们值得使用。从他们的解释:

这是行不通的,因为你不正确自动加载功能。你在做的是自动加载一个叫做的函数,例如/path/to/lt_shell_functions/echome想要要做的是自动加载一个名为echome的函数。

注意:在功能名称中允许使用斜杠/。如果你尝试自动加载一个尚未定义的函数,zsh将会在稍后加载该函数 - 这就是为什么它不会为你打印“自动加载失败”的原因。

我的解决办法: 我们可以提取功能like this名称:

${function_file##/*} 

所以我修改~/.zshrc做到这一点:

autoload ${function_file##/*} || printf "Autoloading $function_file failed\n" 

其工作原理:

Last login: Fri Jun 21 17:21:26 on ttys000 
$ tail -n 12 ~/.zshrc 
if [[ -d $lt_shell_functions_dir ]]; then 
    fpath=($lt_shell_functions_dir $fpath) 
    for function_file in $lt_shell_functions_dir/* 
    do 
     autoload -Uz ${function_file##*/} || printf "Autoloading $function_file failed\n" 
    done 
# unset function_file 
else 
    printf "no $lt_shell_functions_dir exists.\n" 
fi 
$ echome 
I'm in a file