问题描述
如何在 OSX 中从终端暂停(而不是停止)正在运行的脚本,以便稍后从暂停点恢复它?
How can I pause (not stop) a running script from Terminal in OSX, to resume it later from the point it paused?
推荐答案
补充devnull的和DavidW 的 有用的答案:
以下是用于按名称暂停(暂停)/恢复脚本的便利函数,来自任何 shell(不仅仅是启动脚本的那个):
To complement devnull's and DavidW's helpful answers:
Here are convenience functions for suspending (pausing) / resuming a script by name, from any shell (not just the one that started the script):
传递脚本的文件名(没有路径):
Pass the script's filename(s) (without path):
suspend-script someScript ...
及以后:
resume-script someScript ...
更新:添加了用于按名称杀死脚本的附加功能:kill-script someScript ...
Update: Added additional function for killing a script by name: kill-script someScript ...
- 适用于由
bash
或sh
(在 macOS 上实际上只是bash
别名)运行的脚本. - 如果一个脚本的多个实例正在运行,则仅针对最近启动的实例.
- 如果失败(包括找不到指定名称的正在运行的脚本),退出代码将为非零.
suspend-script
和resume-script
:如果脚本进程已经处于想要的状态,则不执行任何操作(不报错).莉>
- Works with scripts run by either
bash
orsh
(which is effectively just abash
alias on macOS). - If multiple instances of a script are running, only the most recently started is targeted.
- Exit code will be non-zero in case of failure (including not finding a running script by the given name).
suspend-script
andresume-script
: if a script process is already in the desired state, no operation is performed (and no error is reported).
函数(例如,将它们放在 ~/.bash_profile
中):
Functions (e.g., place them in ~/.bash_profile
):
suspend-script() {
[[ -z $1 || $1 == '-h' || $1 == '--help' ]] && { echo "Usage: $FUNCNAME scriptFileName ..."$'
'"Suspends the specified bash/sh script(s)."; return $(( ${#1} == 0 )); }
local ec=0
for p in "$@"; do
pkill -STOP -nf '/?(bash|sh)[ ]+(.*/)?'"$p"'( |$)'
&& echo "'$1' suspended."
|| { ec=$?; echo "ERROR: bash/sh script process not found: '$p'" 1>&2; }
done
return $ec
}
resume-script() {
[[ -z $1 || $1 == '-h' || $1 == '--help' ]] && { echo "Usage: $FUNCNAME scriptFileName ..."$'
'"Resumes the specified bash/sh script(s)."; return $(( ${#1} == 0 )); }
local ec=0
for p in "$@"; do
pkill -CONT -nf '/?(bash|sh)[ ]+(.*/)?'"$p"'( |$)'
&& echo "'$1' resumed."
|| { ec=$?; echo "ERROR: bash/sh script process not found: '$p'" 1>&2; }
done
return $ec
}
kill-script() {
[[ -z $1 || $1 == '-h' || $1 == '--help' ]] && { echo "Usage: $FUNCNAME scriptFileName ..."$'
'"Kills the specified bash/sh script(s)."; return $(( ${#1} == 0 )); }
local ec=0
for p in "$@"; do
pkill -nf '/?(bash|sh)[ ]+(.*/)?'"$p"'( |$)'
&& echo "'$1' killed."
|| { ec=$?; echo "ERROR: bash/sh script process not found: '$p'" 1>&2; }
done
return $ec
}
这篇关于在 Mac 终端中暂停正在运行的脚本,然后再继续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!