Bash – How to cancel the rest of a list of commands in Bash

bashcommand linejob-control

In Bash, occasionally I will type in a list of commands and hit Enter, and only later realize that there is a mistake with some command near the end of the list. I know that if I press Ctrl+C it will terminate the currently running command and cancel the rest of the list. Is there any way to cancel the rest of the list without terminating the currently running command?

For example, let's say I have typed something like

foo; bar

or

foo && bar

where foo is a long-running command that it is very important not to interrupt, and bar does something irreversible and unwanted (say, shutdown -h now or rm -rf /). While foo is still running, is there a general way of telling the shell to let foo finish but not to run bar afterwards? (Yes, I could change the permissions on bar so that it's not executable, but that's not particularly convenient if bar is something like rm that I want to use in the meantime, nor will it work if I don't own bar or if bar is a builtin.)

Best Answer

I've observed that using CtrlZ to shift the program to a background process does the trick.

foo && bar

Thanks to @Arkadiusz Drabczyk for pointing it in comments that foo; bar doesn't give control in the required way.

Then:

^Z

[1]+  Stopped                 foo

The command stops only the first task and

fg %1

This brings only task foo to the foreground and completes the task and exits.

PS: This can be checked with two scripts writing to a file. The first one sleeping for a few seconds to give time to be put back.

I'm lost on why the CtrlZ handles only the command running and leaves the rest. Would love to get to know.

Related Question