I have an enormous shell script that I am troubleshoot开发者_如何转开发ing. I often run the script from my home directory with a sudo
. Whenever a find
is executed, I see this error:
find: .: Permission denied
It is true that root does not have access to my home directory (which is the current working directory or .
in the error above), but I'm not asking find
to do anything in my home directory and would rather it leave it alone entirely.
To really drive the point home I ran this:
sudo find /dev -maxdepth 1 -type f
and still get the same error. If the -type -f
is removed the error is appended to the end of the expected results. Of course, if I cd /dev
there is no error..probably since root has access to /dev
. Even though I don't think it's causing problems, it makes the script look buggy. How can I prevent the script from showing these errors?
I ran:
strace find /dev -maxdepth 1
on GNU/Linux (Ubuntu) and it turns out that find
uses fchdir
syscall to traverse the directory tree and finally executes fchdir
to go back to the original working directory. Here's a snippet:
open(".", O_RDONLY|O_NOCTTY|O_NONBLOCK|O_LARGEFILE|O_DIRECTORY|O_NOFOLLOW) = 4
fchdir(4) = 0
... irrelevant ...
write(1, "/dev\n", 5) = 5
open("/dev", O_RDONLY|O_NONBLOCK|O_LARGEFILE|O_DIRECTORY|O_CLOEXEC) = 5
fcntl64(5, F_GETFD) = 0x1 (flags FD_CLOEXEC)
fchdir(5) = 0
... potentially more fchdirs ...
fchdir(4) = 0
close(4) = 0
My hint? cd /tmp
(or some other fully accessible directory) before running find
.
Add a cd /
to the start of the script. Unless you source
it, the script is run in a sub-shell, so your own $PWD
will not be changed. If you do source it, either store $PWD
at the start and cd -- "$PWD"
at the end, or simply cd -
if you don't do any other cd
s in the script.
Try redirecting stderr. For example, you could throw it away:
find /dev 2>/dev/null
精彩评论