Pause a running script in Mac terminal and then resume later
bash, macos, terminal
Solution
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 ...`
and later:
`resume-script someScript ...`
Update: Added additional function for killing a script by name: `kill-script someScript ...`
- 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).
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
}
Problem
How can I pause (not stop) a running script from Terminal in OSX, to resume it later from the point it paused?