14

Suppose there are 2 tasks t1, t2 which can be executed in a serial way as below:

t1 ; t2
# OR
t1 && t2

Now suppose I forgot to run t2 and t1 is already running; can I add t2 to the pipeline so that it gets executed after t1 finishes?

19

Yes you can:

  1. Pause the currently running job with the suspend character by pressing Ctrl+Z.
  2. Type fg or %, add what you want to the list and execute it, e.g.:
    fg ; systemctl suspend # or
    % ; systemctl suspend
    Since fg returns the return value of the job it resumed, list operators like && and || work as expected:
    fg && echo "Finished successfully!" # or
    % && echo "Finished successfully!"

man bash/JOB CONTROL says about the suspend character:

Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. (…) The user may then manipulate the state of this job, using the bg command to continue it in the background, the fg command to continue it in the foreground, or the kill command to kill it. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.

fg is explained in man bash/SHELL BUILTIN COMMANDS:

fg [jobspec]
Resume jobspec in the foreground, and make it the current job. If jobspec is not present, the shell's notion of the current job is used. The return value is that of the command placed into the foreground, or failure if run when job control is disabled or, when run with job control enabled, if jobspec does not specify a valid job or jobspec specifies a job that was started without job control.

Further reading (aside from man bash) on job control:

  • +1 but it's a shame this doesn't work when you forget t3 in t1; t2; t3 or t1 && t2 && t3. – JoL May 8 '18 at 17:19
  • @JoL True that – ^Z^Z and %-;%+;t3 is good enough in some cases, but it's far from being a real solution to the problem. – dessert May 8 '18 at 20:53
2

I saw this method here: https://superuser.com/questions/334272/how-to-run-a-command-after-an-already-running-existing-one-finishes

where you first do Ctrl+z to stop (suspend) the running one then you run the missed command like so: fg && ./missed_cmd.sh and it will run as soon as the fg finishes.

The fg (foreground command) will bring the suspended job online and the && will ensure that the missed command is only run if the first command succeeds.

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.