10

Suppose I do a recursive ls

$ ls -R 

on the root directory.

I get a lot of messages like these -

ls: cannot open directory ./var/lib/sendmail: Permission denied
ls: cannot open directory ./var/lib/sudo: Permission denied
...

Is there a way to avoid displaying the above "cannot open directory" messages?

1 Answer 1

27

Since these are error messages, they are sent to stderr not stdout. The solution is that you redirect stderr:

ls -R 2>/dev/null

Explanation:

Any command has 3 standard file descriptors: standard input (0) (usually the terminal where you type in commands), standard output (1) (usually the terminal where the command prints its output) standard error (2) (by default it's the same as standard output).

Most (if not all) programs/tools print warnings and errors to the standard error file descriptor. Now the file descriptors wouldn't be much use if they were fixed; which is why the shell offers redirection: you can redirect any of the standard file descriptors to any file you want.

Redirecting stdin (to take input from a file instead of from your keyboard):

interactive_program 0< file_with_answers

As you can see this can help you automate the running of simple programs that ask a lot of questions by providing a so-called "answer file" served on standard input.

This can be shortened to

 interactive_program < file_with_answers

as the < makes the redirection clear (from the file to the program)

Similarly, stdout can be redirected via 1>... or >... or >>... (append to an existing file instead of truncating it)

Standard error redirection requires that you specify the file descriptor explicitly like so: 2>..., so what the above does is it directs all errors to the special file /dev/null which is sort of a black hole for bits.

Relevant reading on redirection as provided by MattDMo in the comments below.

3
  • what is 2> ? Can you please explain?
    – CodeBlue
    Commented Jul 11, 2013 at 20:42
  • 3
    It's a redirection command. > will redirect stdout or standard output, 2> redirects stderr or standard error. 1> is the same as >, so you can see where the 2 comes from. You can read more about I/O redirection here on the Linux Documentation Project.
    – MattDMo
    Commented Jul 11, 2013 at 20:46
  • @CodeBlue See my updated answer.
    – Joseph R.
    Commented Jul 11, 2013 at 20:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .