昨天我正在编写一个 shell 脚本,需要获取 .zshrc 来更新当前的 zsh shell。
我发现源代码过程需要更多时间,因为我继续这样做source .zshrc
。
source
或的文档.
如下:
. file [ arg ... ]
Read commands from file and execute them in the current shell environment.
If file does not contain a slash, or if PATH_DIRS is set, the shell looks in the components of $path to find the directory containing file. Files in the current directory
are not read unless `.' appears somewhere in $path. If a file named `file.zwc' is found, is newer than file, and is the compiled form (created with the zcompile builtin)
of file, then commands are read from that file instead of file.
If any arguments arg are given, they become the positional parameters; the old positional parameters are restored when the file is done executing. However, if no arguments
are given, the positional parameters remain those of the calling context, and no restoring is done.
If file was not found the return status is 127; if file was found but contained a syntax error the return status is 126; else the return status is the exit status of the
last command executed.
source file [ arg ... ]
Same as `.', except that the current directory is always searched and is always searched first, before directories in $path.
那么问题是为什么最后的来源比开始需要明显的时间?
答案1
source
(来自 csh)或.
(来自 Bourne shell)是 shell 的内置命令,它们请求 shellread
并解释作为参数传递的文件中存储的 shell 代码。
运行所需的时间就是读取和解释该代码所需的时间,因此一切都取决于该代码的作用。
例如,如果该代码具有:
var=$var$var
每次运行时变量的大小都会加倍$var
,很容易想象,运行该代码的次数越多,运行它所需的时间就越多,因为每次运行它时需要复制的数据量都会加倍。
要找出哪个命令花费最多时间,您可以执行以下操作:
PS4='%D{%T.%3.} %N:%i> '; set -o xtrace; source ~/.zshrc
这将打印正在运行的每个命令,并带有毫秒精度的时间戳。