Why can I see the output of background processes?

The & directs the shell to run the command in the background, i.e, it is forked and run in a separate sub-shell, as a job, asynchronously.

Note that when you put & the output - both stdout and stderr - will still be printed onto the screen. If you do not want to see any output on the screen, redirect both stdout and stderr to a file by:

myscript > ~/myscript.log 2>&1 &

Usually you may want to discard the stderr by redirecting it to /dev/null if you are not worried about analyzing errors later.

You can also even run commands/scripts at the same time, in separate sub-shells. For eg;

./script1 & ./script2 & ./script3 & 

A background job can be brought back to the command line before it finishes with the command:

fg <job-number>

The job-number can be obtained by running

jobs

When you use &, the process is running in background. But its standard output is still the terminal.

In fact, you may run ping 8.8.8.8 & and find / -name '*test*' & at the same time (resulting in a mixed output), but you may not run ping 8.8.8.8 and find / -name '*test*' at the same time on the same shell.

If you don't want to see anything, use something like ping 8.8.8.8 &> /dev/null &.


Additionally, you may want to learn about nohup and disown.

Tags:

Command Line