I’m supposed to look for all files named temp
.
Would I just do: find . -name "temp"
Then I’m supposed to make sure no error messages pop up
Would I just add the 2>/dev/null
at the end of the previous command?
I’m supposed to look for all files named temp
.
Would I just do: find . -name "temp"
Then I’m supposed to make sure no error messages pop up
Would I just add the 2>/dev/null
at the end of the previous command?
The command
find . -name temp
would find all names that are temp
. This includes all sorts of files, e.g. regular files, directories, sockets, symbolic links etc.
If you want to find only regular files, then use the -type f
test:
find . -name temp -type f
To hide the errors that this may provoke (by trying to access inaccessible directories):
find . -name temp -type f 2>/dev/null
That is, redirect the standard error stream of find
to /dev/null
(which discards all errors).
If you want to avoid errors, i.e. not hide errors, then make sure that you don't try to enter directories that you don't have access to. With GNU find
, this may conveniently be done using
find . -type d ! \( -readable -executable \) -prune -o -name temp -type f -print
The -type d
test will be true for any directory, and with GNU find
, the negated -executable -readable
test will be true if the current pathname refers to a thing that is not both executable and readable for the current user. A directory is accessible if it is executable by you, and you can list a directory's contents if it's also readable. The -prune
"prunes" the directory from the search tree, i.e. it makes find
not enter it.
The -o
is a logical "OR" operation. When -o
is not used, the default is -a
for "AND". The tests and actions specified are evaluated in a left-to-right manner.
The final -print
prints out all pathnames that passes all the tests.
Would you want to do something to the found files, then do so with an action executed by find
. To delete them, for example, add -delete
to the end of the command (or change -print
to -delete
). To do a more generic action, you may want to loop over them. You do that using
find . -type d ! \( -readable -executable \) -prune -o -name temp -type f \
-exec sh -c '
for pathname do
# code that uses "$pathname" goes here
done' sh {} +
See also