In this following bash script I don't understand what the 2 means:
function kill_process()
{
kill -9 $(lsof -i:$1 -t) 2> /dev/null
}
I can see that the it is redirecting the output to the null device but what does the 2 mean?
The N>
syntax in Bash means to redirect a file descriptor to somewhere else. 2
is the file descriptor of stderr
, and this example redirects it to /dev/null
.
What this means in simple terms: ignore error output from the command. For example, if kill
cannot stop a process because it doesn't exist, or because the current user doesn't have the permission to do that, it would print messages on stderr
. By redirecting stderr
to /dev/null
, you effectively suppress these messages.
A number in front of the >
tells the shell which file descriptor to redirect into the file. If you leave the number off, it defaults to 1 - which is the same as standard output, stdout for short, which most commands write their output to. However, programs in the terminal actually have two output channels by default, the other one being standard error. The purpose of stderr is to allow errors to be sent to the terminal even when standard output is redirected into a file or pipe; they both go to the terminal by default. But you can redirect stderr if you want, and that's what this code is doing, since stderr's file descriptor number is 2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With