Bash: execute one command after another, even if I paused the first (Ctrl-z)

I know in bash I can run one command after another, separating them with a semicolon, for example

$ command1; command2 

Or, if I want command2 to command2 executed only if command1 succeeds using && :

 $ command1 && command2 

This works, but if I pause command1 with Ctrl-z , in the first case it starts command2 right away, and in the second case it doesn't start it at all. How can I run the commands sequentially, but still I can pause the first command, but not execute the second run until I restarted it (using fg ) and it finishes? I would prefer it to be as easy as typing, as I would like to do this interactively. Or maybe I just need to set the option somewhere.

By the way, what is the correct term for Ctrl-z ?

+57
bash shell command signals suspend
Nov 28 '12 at 7:53
source share
2 answers

The following should do it:

 (command1; command2) 

Pay attention to the added brackets.

+80
Nov 28 '12 at 8:03
source share

In Bash, when you put a task in the background (using CTRL + Z or &), it does not wait for the task to complete and gives an exit code with a zero value (success). You have noticed a lot of this, and it is documented in the man pages.

The behavior of the logical AND, & &, is that it checks from left to right. Each part must be successful, therefore, if the first is unsuccessful, the second will not work. So with && he runs the commands from left to right until one of them works. The definition of success is the exit code ($?), Equal to zero.

Contrast this with the logical "OR", ||, which runs commands from left to right until one of them works.

An explanation of the subshell solution that @NPE provides can also be found on the man pages:

Compound commands and command sequences of form 'a; b; c is not handled gracefully when the process pauses. When the process stops, the shell immediately executes the next command in sequence. It is enough to place the sequence of commands between parentheses to force it to be included in the subshell, which can be stopped as a unit.

The correct term for CTRL + Z is the pause symbol, again from the man pages:

Entering a pause character (usually ^ Z, Control-Z) during the start of a process causes the process to stop and return to bash control.

(Sorry to quote the man pages so much, but they are really your friends and deserve attention)

If you look at stty -a , you will see something like this:

 susp = ^Z; 

So you can change it, hence the phrase β€œusually”. Don't do this though, it confuses the devil of all. The terminal driver triggers the SIGTSTP signal, which is trapped by bash.

+11
Nov 28 '12 at 8:45
source share



All Articles