【问题标题】:startup .zshrc to autoload bash script as function启动 .zshrc 以将 bash 脚本作为函数自动加载
【发布时间】:2013-09-26 20:46:53
【问题描述】:

我的 .zshrc 底部有

[[ -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),其中有一些我想作为 zsh 函数加载的 bash 脚本。我希望能够从命令提示符执行类似“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 时:

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

【问题讨论】:

    标签: shell zsh zshrc


    【解决方案1】:

    应注意:我不知道为什么这没有打印“自动加载失败”,即使在仔细阅读 man zshbuiltins 之后也是如此。幸运的是,如果您遇到困难(邮件列表和 IRC),zsh 有一个很好的社区——它们值得使用。从他们的解释中:

    这不起作用,因为您没有正确地自动加载函数。你正在做的是自动加载一个函数,例如,/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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-27
      • 1970-01-01
      • 2021-09-13
      相关资源
      最近更新 更多