Z Shell “autoload” builtin - what is it good for?

雨燕双飞 提交于 2019-12-20 16:47:38

问题


I have been using the Z shell for a while now, and I am starting to be curious. One thing I have stumbled at when writing my own functions is "autoload".

According to the zshbuiltins(1) man page autoload is "equivalent to functions -u" (with an exception), which is "equivalent to typeset -f" (with an exception). However, after looking at the autlooad use of, say functions/Prompts/promptinit, I think I have an idea what it does.

I think of autoload as, well, kind of "import" statement.

But why is "autoload foo" superior to "source bar"? I don't get that.


回答1:


As stated in the zsh documentation:

A function can be marked as undefined using the autoload builtin (or functions -u or typeset -fu). Such a function has no body. When the function is first executed, the shell searches for its definition using the elements of the fpath variable. [...]

autoload allows for functions to be specified without a body which then get automatically loaded when used ;)

source however takes as argument a script which is then executed in the environment of the current session - i.e. you will retain all changes the script does to the environment, which is not the case when just executing the script.

I think this feature is beneficial when having lots of utilities in functions. It allows for faster startup (all the code for the autoload functions need not be loaded) and may keep the memory footprint of the shell smaller.



来源:https://stackoverflow.com/questions/4493173/z-shell-autoload-builtin-what-is-it-good-for

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!