5

I have cmd2 that needs to follow after cmd1 completes. I need to pause cmd1 sometimes.

I type in

$ cmd1 && cmd2

and then press Ctrl+Z (Stop) to stop cmd1. Now, cmd1 is paused but when I resume, it does not start cmd2 after completion of cmd1.

I type in

$ cmd1 ; cmd2

and then I press Ctrl+Z (Stop) to stop cmd1. Now cmd1 is paused but it immediately starts cmd2. However, I wish to start cmd2 only after cmd1 finishes.

I did some research and someone suggested an elegant way in zsh but I wonder if there is an elegant way of doing it in bash.

codeforester
  • 39,467
  • 16
  • 112
  • 140
Lance Ruo Zhang
  • 401
  • 4
  • 12
  • Related: https://stackoverflow.com/questions/13600319/bash-run-one-command-after-another-even-if-i-suspend-the-first-one-ctrl-z – codeforester Jun 17 '17 at 14:38

1 Answers1

11

Run it in a subshell:

(cmd1 && cmd2)

Example:

$ (sleep 5 && echo 1)                        # started the command chain
^Z
[1]+  Stopped         ( sleep 5 && echo 1 )  # stopped before `sleep 5` finished
$ fg                                         # resumed
( sleep 5 && echo 1 )
1                                            # `sleep 5` finished and `echo 1` ran
codeforester
  • 39,467
  • 16
  • 112
  • 140
  • 1
    Thanks! I didn't know it is that easy and overthink-ed myself! Thanks for the help. – Lance Ruo Zhang Jan 18 '17 at 06:44
  • 2
    @codeforester, I didn't understand that why does it needs a subshell ? – sat Jan 18 '17 at 06:53
  • I think the command buffer gets flushed when we stop and resume. In case of the subshell, it already has the full command line and it is not reading it from an input device. That's my guess. – codeforester Jan 18 '17 at 06:59
  • @codeforester, I don't think so. Because, It is able to resume `cmd1`. Why not `cmd2` ? Even though, we have entered as a single command line. – sat Jan 18 '17 at 07:27