shell - 如何组织我的 ZSH 代码?单个文件与多个文件中的多种方法

标签 shell zsh

出于某种目的,我正在 ZSH 中编写一堆函数,命名为 X_somename,用户将从命令行运行它们。大约有 20 个。

我想知道哪种方法更优化(就代码组织、性能等而言)-

  1. 将所有内容放在一个文件 X.zsh 中,其中包含函数定义,每个函数都有一个 X_somename 形式的名称,然后在 .zshrc 中源 X.zsh

  2. 创建单独的文件,每个文件的名称如 X_somename,并将包含它们的文件夹包含在 PATH 环境变量中

谢谢。

最佳答案

通常的做法是定义函数,每个文件一个,并将文件夹放在 fpath 中。您还应该标记自动加载的功能。函数不应该是 shell 脚本(因此不要将它们添加到您的路径中,而是添加到您的 fpath (函数路径)中)。

来自http://zsh.sourceforge.net/Doc/Release/Functions.html

fpath=(~/myfuncs $fpath)
autoload myfunc1 myfunc2 ...

我实际上做的是:

if [[ -d $ZDIR/code ]]; then
   # Autoload shell functions from $ZDIR/code with the executable bit on.
   for func in $ZDIR/code/*(N-.x:t); do
      unhash -f $func 2>/dev/null
      autoload +X $func
   done
fi

请注意,有 KSH 风格的函数,您可以在上面链接的页面中添加 function foo():

If the KSH_AUTOLOAD option is set, or the file contains only a simple definition of the function, the file’s contents will be executed. This will normally define the function in question, but may also perform initialization, which is executed in the context of the function execution, and may therefore define local parameters. It is an error if the function is not defined by loading the file.

Otherwise, the function body (with no surrounding ‘funcname() {...}’) is taken to be the complete contents of the file. This form allows the file to be used directly as an executable shell script. If processing of the file results in the function being re-defined, the function itself is not re-executed. To force the shell to perform initialization and then call the function defined, the file should contain initialization code (which will be executed then discarded) in addition to a complete function definition (which will be retained for subsequent calls to the function), and a call to the shell function, including any arguments, at the end.

关于shell - 如何组织我的 ZSH 代码?单个文件与多个文件中的多种方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24583863/

相关文章:

linux - linux将文件从usb复制到桌面脚本

linux shell进程文本

zsh - 使用通配符扩展来回显 zsh 中的所有变量

shell - ipython shell awk : Escaping "$" sign

python - zsh:当我尝试在 venv 中运行应用程序时,中止 python 错误

bash - 用于列出给定目录中的文件以及它们是文件还是目录的 Shell 脚本

node.js - 创建独立的 Node js 应用程序安装程序

linux - 文件的最后两行相同表示触发电子邮件

zsh - 将 PS1 Coloring 从 .bashrc 转换为 ZSH (.zshrc)

ubuntu - 在终结者终端模拟器中运行 Zsh 时修复 .zshrc 中的键设置(Home/End/Insert/Delete)