Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I would like to know what is the behaviour of Ctrl+Z and fg in bash when wanting to append commands to be executed after a running command has finished. For example, in the sequence for commands below, I would expect the console to display "1", then "2", then "3", then "4", but I only get the last command, echo 4, after sleep 30 finishes:

avilella@magneto:~$ sleep 30 && echo 1 
[1]+  Stopped                 sleep 30
avilella@magneto:~$ fg && sleep 5 && echo 2
sleep 30
[1]+  Stopped                 sleep 30
avilella@magneto:~$ fg && sleep 5 && echo 3
sleep 30
[1]+  Stopped                 sleep 30
avilella@magneto:~$ fg && sleep 5 && echo 4
sleep 30

Any ideas?

share|improve this question
What's the real problem? Are you interested in how ^Z & fg work, or are you trying to script a solution to a specific problem? – PriceChild Nov 27 '11 at 0:18
why don't you run jobs after every Ctrl-Z and see what you have running – Rich Homolka Nov 27 '11 at 0:50

Control-Z suspend a job (not your shell command line), so all the other commands will run without waiting for it. Seems that when you stop a job the shell try to run the next one but as you used && and the previous command was not finished OK (was not finished at all but paused), the command with && is discarded. On the other hand if you use ; instead && for a second command in the command line, then you would see that the second command gets executed when the first one is paused:

$ perl -e '$|=1;for (1..5){ sleep 1;print}print qq{END\n} ';echo test_z00000000000000
[1]+  Stopped                 perl -e '$|=1;for (1..5){ sleep 1;print} '
$ fg
perl -e '$|=1;for (1..5){ sleep 1;print} '
share|improve this answer

It's not fg you want; it might be wait. E.g.

$ cp large.file some/where
[1]+ 22224 suspended  cp
$ wait && beep  # beep when first command completes

For more info:

$ help wait
share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .