Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect stderr to /dev/null

Tags:

linux

grep

I am using the following command on a Unix server:

find . -type f -name "*.txt" | xargs grep -li 'needle' 

Since grep -R is not available, I have to use this find/xargs solution. Every time a file cannot be opened, grep tells me this:

grep: can't open "foo.txt"

I want to get rid of this message, so I tried to redirect stderr to /dev/null, but somehow this is not working.

find . -type f -name "*.txt" | xargs grep -li 'needle' 2>/dev/null 

I want to preserve stdout (i.e. write the results to the console), and only hide these grep error messages. Instead of 2>, I also tried &>, but this also did not work. How can I fix this?

like image 399
r0f1 Avatar asked Jun 26 '17 11:06

r0f1


People also ask

How do I send stderr to Dev Null?

In Unix, how do I redirect error messages to /dev/null? You can send output to /dev/null, by using command >/dev/null syntax. However, this will not work when command will use the standard error (FD # 2). So you need to modify >/dev/null as follows to redirect both output and errors to /dev/null.

What does redirect to Dev Null do?

The operator '>' , called a redirection operator, writes data to a file. The file specified in this case is /dev/null. Hence, the data is ultimately discarded. If any other file were given instead of /dev/null, the standard output would have been written to that file.

How do I redirect stderr?

Understanding the concept of redirections and file descriptors is very important when working on the command line. To redirect stderr and stdout , use the 2>&1 or &> constructs.

What does Dev Null 2 &1 mean?

/dev/null is a special filesystem object that discards everything written into it. Redirecting a stream into it means hiding your program's output. The 2>&1 part means "redirect the error stream into the output stream", so when you redirect the output stream, error stream gets redirected as well.


1 Answers

In order to redirect stderr to /dev/null use:

some_cmd 2>/dev/null 

You don't need xargs here. (And you don't want it! since it performs word splitting)

Use find's exec option:

find . -type f -name "*.txt" -exec grep -li needle {} + 

To suppress the error messages use the -s option of grep:

From man grep:

-s, --no-messages Suppress error messages about nonexistent or unreadable files.

which gives you:

find . -type f -name "*.txt" -exec grep -lis needle {} + 
like image 118
hek2mgl Avatar answered Sep 20 '22 21:09

hek2mgl