From The System Administrator Zone

Using test

One way to eliminate of the error messages is to include checks for file or directory permissions, using the test command, before doing anything.

Checking Permissions on a Directory

For example, if you are looking for a file name TEST.TXT and are having problems with directories that you are not allowed to enter, you can skip them with:

find . \( -type d ! -exec test -x {} -a -r {} \; -prune \) -o \( -name TEST.TXT ) -exec ls -ld {} \;

The Key Options

-type d ! -exec test -x {} -a -r {} \; -prune 

This used the test command to check the execute and read permissions of the directory. The -prune option will cause it to skip any directory that fails the test.

IO Redirection

Unix utilities open three files automatically when a program starts up. These files are commonly known as stdin (standard input -- file descriptor 0), stdout (standard output -- file descriptor 1), and stderr (standard error -- file descriptor 2).

Default assignments for these files when a program starts are /dev/tty, which is the device name for your terminal. The stdin file is assigned to the keyboard of your terminal. stdout and stderr are assigned to the screen of your terminal.

Naming of the Redirection Operators

The output redirection operator defaults to 1. Thus > and 1> are equivalent.

The input redirection operator defaults to 0. Thus < and <0 are equivalent.

The standard error, file descriptor 2, requires that its number be explicitly included in the redirection symbol.

For clarity, following examples use 1> to redirect standard output because it helps show how the redirection works.

Logging Output to Separate Files

One method of saving the command output would be to create separate logs for each type of output:

find / -name *.exe -exec ls -l {} \; 1>files_found.txt 2>errors.txt

Logging Output to the Same Device - >&

It is also possible to redirect an output by attaching it to an already open descriptor using the >& redirection operator. Standard output of find is redirected to the file output.txt. The 2>&1 redirection command instructs the shell to attach the output from standard error (2) to the output of standard output (1). Now both standard output and standard error are sent to output.txt.

find / -name *.exe -exec ls -l {} \; 1>output.txt 2>&1

The Order of Redirection is Important

The order of redirection is important. In the following example, the output of file descriptor 2 (standard error) is attached to file descriptor 1. At this point, standard output is still attached to the terminal, so standard error is sent to the terminal. The next redirection sends standard output to result.txt. This redirection doesn't drag file descriptor 2 along with it, so standard error is left pointing to the terminal device.

find / -name *.exe -exec ls -l {} \; 2>&1 1>output.txt
find: /home/userone: Permission denied
find: /home/usertwo: Permission denied