在Mac终端中暂停正在运行的脚本,然后稍后恢复 [英] Pause a running script in Mac terminal and then resume later

查看:263
本文介绍了在Mac终端中暂停正在运行的脚本,然后稍后恢复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从OSX的Terminal中暂停(而不是停止)正在运行的脚本,以便稍后从暂停的点继续执行脚本?

How can I pause (not stop) a running script from Terminal in OSX, to resume it later from the point it paused?

推荐答案

以补充@devnull和@DavidW的有用答案:
以下是便捷功能,用于从 any 外壳程序(不仅仅是启动脚本的外壳程序)中按名称挂起(暂停)/恢复脚本:

To complement @devnull 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 ...

  • 使用由bashsh(实际上只是OSX上的bash别名)运行的脚本.
  • 如果脚本的多个实例正在运行,则仅以最近启动的为目标.
  • 如果失败(包括未找到给定名称的运行脚本),退出代码将为非零.
  • suspend-scriptresume-script:如果脚本进程已经处于所需状态,则不执行任何操作(并且不报告错误).
  • Works with scripts run by either bash or sh (which is effectively just a bash alias on OSX).
  • 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 and resume-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 ..."$'\n'"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 ..."$'\n'"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 ..."$'\n'"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终端中暂停正在运行的脚本,然后稍后恢复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆