2

Everyone keeps saying adding & to the end of a command puts it in the background, I tried this with a ping command, however it still appeared in the foreground, the only change is it wouldn't stop after ctrl c. What am I doing wrong? I ran ping 8.8.8.8&. If someone could explain this it would be appreciated, I just want the command to be ran in the background so I can use my server while it does the ping.

robert
  • 31
  • 9
  • Your ping **is** running in background. You can recognize this, because a line similar to `[1] 4711` is printed, where 4711 (or whatever) is the PID of the background process. If you don't want to see the output of the command cluttering your terminal, prefix it with `nohup`: `nohup ping 8.8.8.8 &`. See _man nohup_ for details. – user1934428 Jan 22 '21 at 12:06

1 Answers1

6

Adding & does run the process in the background. But, the program would still continue to write output (to standard output & standard error streams) as usual.

You will have to silence that output, e.g. through a command-line switch, or by redirecting the output to a file.

In the case of ping, you can run:

ping 8.8.8.8 -q &

Alternatively, you can do for example:

ping 8.8.8.8 > log.txt 2>&1 &

This will redirect the standard output & standard error to the file log.txt -- useful if you want to inspect or otherwise make use of the output.

If you don't care about the output, then just redirect to /dev/null (special device file) instead, to discard the output:

ping 8.8.8.8 > /dev/null 2>&1 &

Perhaps you still want to see any errors, or have the errors go to a separate file, in which case do the following:

# Errors in errors.txt and output in log.txt
ping 8.8.8.8 > log.txt 2> errors.txt &

# Output in log.txt and errors to standard error as usual
ping 8.8.8.8 > log.txt &
costaparas
  • 5,047
  • 11
  • 16
  • 26
  • 2
    To redirect both stdout and stderr to the same place, you need to put the `2>&1` second (e.g. `ping 8.8.8.8 > /dev/null 2>&1 &`). See ["Shell redirection i/o order"](https://stackoverflow.com/questions/17975232/shell-redirection-i-o-order). – Gordon Davisson Jan 22 '21 at 17:08
  • Thanks @gordon, you're right, fixed it – costaparas Jan 22 '21 at 23:56
  • Thanks for the help, for anyone viewing this thread I recommend sending the output to another file rather than adding -q to ping since -q will still display the fact that the ping has begun which for me didn't work since I needed to run multiple pings at once. – robert Jan 23 '21 at 06:05