Shell – Press any key to pause shell script, press again to resume

shell-script

I've written a shell script for testing an API that copies files and echoes its progress after each one.

There is a two second sleep between each copy, so I would like to add the ability to press any key to pause the script to allow deeper testing. Then press any key to resume.

How can I add this in as few lines as possible?

Best Answer

You don't need to add something to your script. The shell allows such a functionality.

  • Start your script in a terminal.
  • While is is running and blocking the terminal use ctrl-z. The terminal is released again and your see a message that the process is stopped. (It is now in the porcess state T, stopped)
  • Now do whatever you want. You can also start other processes/scripts and stop them with ctrl-z.
  • Type jobs in the terminal or list all stopped jobs.
  • To let your script continue, type fg (foreground). It resumes the job back into the foreground process group and the jobs continues running.

See an example:

root@host:~$ sleep 10 # sleep for 10 seconds
^Z
[1]+  Stopped                 sleep 10
root@host:~$ jobs # list all stopped jobs
[1]+  Stopped                 sleep 10
root@host:~$ fg # continue the job
sleep 10
root@host:~$ # job has finished
Related Question