mar*_*aft 9 zsh background-process
当我在运行 zsh 的终端中键入以下内容时(每一行都是一个命令)
babel www/scripts6/lib/data.js > www/scripts/lib/data.js &
babel www/scripts6/lib/user.js > www/scripts/lib/user.js &
babel www/scripts6/lib/profile.js > www/scripts/lib/profile.js &
babel www/scripts6/lib/d3-and-svg.js > www/scripts/lib/d3-and-svg.js &
babel www/scripts6/main.js > www/scripts/main.js &
while [[ $(jobs) =~ 'babel' ]]; do echo 'moo'; done
Run Code Online (Sandbox Code Playgroud)
它停了大约 3 秒钟,然后停止。但是当我在文件moo.zsh 中放入完全相同的代码然后在我的终端中运行它时
zsh moo.zsh
Run Code Online (Sandbox Code Playgroud)
它在不到 1 秒内完成,并且根本没有哞哞。为什么会这样?
cuo*_*glm 11
在非交互式 shell 中,您没有完整的作业控制权。当您开始jobs
执行命令替换时,它会在子 shell 中运行。在这个子 shell 中,没有作业在运行,你什么也没有。
在交互式 shell 中,设置了MONITOR,为您提供完整的作业控制。在这种情况下,zsh
当您进入子外壳时将所有作业存储在一个表中,如果子外壳中没有作业,则将使用该作业表。
在zsh
4.3 及更高版本中,您可以通过放置-m
shebang 行来打开非交互式 shell 中的作业控制:
#!/usr/bin/zsh -m
Run Code Online (Sandbox Code Playgroud)
或使用setopt
:
setopt monitor
: The rest of script goes here
Run Code Online (Sandbox Code Playgroud)
检查作业状态的更好方法是:
#!/usr/bin/zsh
zmodload zsh/parameter
babel www/scripts6/lib/data.js > www/scripts/lib/data.js &
babel www/scripts6/lib/user.js > www/scripts/lib/user.js &
babel www/scripts6/lib/profile.js > www/scripts/lib/profile.js &
babel www/scripts6/lib/d3-and-svg.js > www/scripts/lib/d3-and-svg.js &
babel www/scripts6/main.js > www/scripts/main.js &
while (( ${#jobstates} )); do
print "moo"
done
Run Code Online (Sandbox Code Playgroud)
无论如何,您可以使用内置wait 等待所有子进程:
babel www/scripts6/lib/data.js > www/scripts/lib/data.js &
babel www/scripts6/lib/user.js > www/scripts/lib/user.js &
babel www/scripts6/lib/profile.js > www/scripts/lib/profile.js &
babel www/scripts6/lib/d3-and-svg.js > www/scripts/lib/d3-and-svg.js &
babel www/scripts6/main.js > www/scripts/main.js &
# Wait for all children
wait
echo END
Run Code Online (Sandbox Code Playgroud)