32

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

4 Answers 4

71

If you're using BASH as the shell (which is the default shell on a Mac), you can use BASH's built in job control capabilities.

If the script is running in the foreground of your terminal, you can press Control-Z to pause the script. This will suspend the running of the script.

To restart it, type jobs and you'll see the suspended job listed there. Type fg or more specific fg %x where x is the number of the suspended job.

$ test.pl   # Test script (prints out Foo every two seconds
Foo!
Foo!
^Z
$  # Job has been suspended
$ jobs
[1] + Stopped                  ./test.pl
$ fg %1  #Restarts Job #1
Foo!

The Control-Z key that suspends the job is the default, but could be modified. The stty can change this and will show you the current default:

$ stty -a     
speed 9600 baud; 40 rows; 120 columns;
lflags: icanon isig iexten echo echoe -echok echoke -echonl echoctl
        -echoprt -altwerase -noflsh -tostop -flusho pendin -nokerninfo
        -extproc
iflags: -istrip icrnl -inlcr -igncr ixon -ixoff ixany imaxbel iutf8
        -ignbrk brkint -inpck -ignpar -parmrk
oflags: opost onlcr -oxtabs -onocr -onlret
cflags: cread cs8 -parenb -parodd hupcl -clocal -cstopb -crtscts -dsrflow
        -dtrflow -mdmbuf
cchars: discard = ^O; dsusp = ^Y; eof = ^D; eol = <undef>;
        eol2 = <undef>; erase = ^H; intr = ^C; kill = ^U; lnext = ^V;
        min = 1; quit = ^\; reprint = ^R; start = ^Q; status = ^T;
        stop = ^S; susp = ^Z; time = 0; werase = ^W;

You can see the very last line has susp = ^Z. This is the key that will suspend your script. In this case, it's Control-Z.

You can also use the bg command to make a suspended job run in the background. However, that background job will terminate when you close the shell/Terminal Window unless you had prepended nohup to the front of the command.

2
  • 7
    I think this deserves the tick
    – geotheory
    Oct 23, 2014 at 10:16
  • 3
    Excellent! This definitely deserves to be marked as the answer. May 13, 2018 at 3:42
11

Find the process ID of the running script.

To stop (or what you refer to as pause) the script, say:

kill -SIGSTOP PID

To resume the stopped (or paused) process, say:

kill -SIGCONT PID

(where PID refers to the numeric process ID.)

4
  • 7
    In addition to that, possibly, but not always, he can also press Ctrl-Z to pause, and later run fg to continue.
    – janos
    Dec 18, 2013 at 5:22
  • @janos You're right, but as you've mentioned but not always.
    – devnull
    Dec 18, 2013 at 5:41
  • @janos can you provide some pointers to search for more information on the solution you mentioned? Would like to read about the edge cases you mentioned.
    – Jikku Jose
    Dec 18, 2013 at 6:39
  • 1
    @JikkuJose you can read about what I mentioned in the JOB CONTROL section of man bash
    – janos
    Dec 18, 2013 at 6:51
4

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
}
2
  • 1
    Thanks but imagine, I am executing a set of commands (say through pipes or ;). Is there a way to pause it when there is no name associated for it?
    – Jikku Jose
    Jan 1, 2014 at 2:50
  • 1
    @JikkuJose: Your best bet is to wrap such commands in a script. Otherwise, each script executed as part of the multi-command string or pipe will show as a separate process and you couldn't target the thing as a whole. Also note that with ;-separated commands a subsequent command will not start until the preceding one either terminates or explicitly starts a background task. Also note that I fixed minor bugs in the functions and added a kill-script function.
    – mklement0
    Jan 2, 2014 at 0:03
1

echo Press any key to continue... read blah

Then just don't do anything with the variable. This is as close to the pause functionality that I've used in DOS batch scripts that I've come across.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.