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

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

问题描述

如何在 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 ...

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

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