1

I have found a behavior of shell I don't understand. When you execute

echo foo > /tmp/bar & exit

, the terminal is closed. But when you execute

exit & echo foo > /tmp/bar

, the terminal stays open and something like

[1] 4001

is printed on it.

The output of the first version can be seen, too, if you log into a different account using su, because then, only the session of the user you logged in to using su is ended and your terminal stays open. It's something like:

[2] 13777
exit
[1]+  Done                    exit

Why isn't the session ended if exit is the first command?

Just in case you can't replicate this on your Unix system: I'm using Ubuntu 16.04.

4

Your first command,

echo foo > /tmp/bar & exit

starts a subshell in the background to run echo foo > /tmp/bar, and exits (the foreground shell). This closes your terminal, in the same way as simply typing exit. The background shell won't stay around very long at all, so you won't get a race; but if you do this with a longer-running command, depending on your shell and your options, you'll get different behaviours:

sleep 60 & exit

might not exit but complain that you have running jobs instead.

In both these cases, the shell does print a line of the form [1] 7149 but if your terminal closes you won't have time to see it.

Your second command,

exit & echo foo > /tmp/bar

starts a subshell in the background to run exit, which exits (from the subshell), and runs echo foo > /tmp/bar. So the “main” shell doesn't exit and the terminal stays open, which allows you to see

[2] 13777

followed by

exit

(printed by the shell exiting) and then

[1]+  Done                    exit

(printed by the main shell when the background shell exits).

2
  • Is which command is executed in the subshell and which one in the original one documented behavior or up to implementation?
    – UTF-8
    Dec 9 '16 at 21:36
  • 2
    It's whichever command is followed by &; see for example the Bash manual for documentation on this. Dec 9 '16 at 21:45

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.