Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of 2 in 2> /dev/null

Tags:

bash

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?

like image 799
dagda1 Avatar asked Nov 21 '16 06:11

dagda1


2 Answers

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.

like image 103
janos Avatar answered Oct 21 '22 02:10

janos


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.

like image 32
Mark Reed Avatar answered Oct 21 '22 04:10

Mark Reed