Unix: Why is my error not triggering?
In filelist, Update, filelist is a file
hello/noReadPermissions1.txt
hello/noReadPermissions2.txt
hello/noReadPermissions3.txt
the file has no read permissions -w------
, however, directory has 700
, but I am trying to read the file.
while read line; do
[ ! -r "$line" ] && echo "Cannot Read this"
done < filelist
It's not triggering! I don't understand why开发者_JS百科, my one and only guess is: the test command is starting in another process. If so, what's a work around?
Actually, it works for me in bash:
while read line; do [ ! -r "$line" ] && echo "no file" ; done
gives me the file name as output if the file exists and is readable, and "no file" if not.
Are you using bash?
Update:
Wait, are you just trying to read the contents of the file?
then
if [ -r $filelist ]
then
while read line
do
# something with line
done < $filelist
fi
Update 2:
Okay, so you have something like
$ touch noreadme
$ chmod a-r noreadme
$ ls -l noreadme
--w------- 1 chasrmartin staff 0 Dec 12 23:16 noreadme
and do
$ while read line; do [ ! -r "$line" ] && echo "no line" ; done < noreadme
and should get
-bash: noreadme: Permission denied
You never get your error message because before the while look even starts, the shell detects it can't read the file. The open(2)
call fails, and the whole line is ended.
The test command is not running in a subshell and would produce output you can see even if it were. It's not entirely clear what you're doing. I believe you're doing one of these two things:
$ mkdir /tmp/readtest
$ cd /tmp/readtest
$ touch noReadPermission{1,2,3}.txt
$ chmod 200 noReadPermission{1,2,3}.txt
$ ls noReadPermission* > filelist
$ ls -l
-rw------- 1 user group 78 Dec 13 11:57 filelist
--w------- 1 user group 0 Dec 13 11:57 noReadPermissions1.txt
--w------- 1 user group 0 Dec 13 11:57 noReadPermissions2.txt
--w------- 1 user group 0 Dec 13 11:57 noReadPermissions3.txt
$ while read line; do [ ! -r "$line" ] && echo "Cannot Read $line"; done < filelist
Cannot Read noReadPermissions1.txt
Cannot Read noReadPermissions2.txt
Cannot Read noReadPermissions3.txt
$ chmod a-r filelist
$ ls -l
--w------- 1 user group 78 Dec 13 11:57 filelist
--w------- 1 user group 0 Dec 13 11:57 noReadPermissions1.txt
--w------- 1 user group 0 Dec 13 11:57 noReadPermissions2.txt
--w------- 1 user group 0 Dec 13 11:57 noReadPermissions3.txt
$ while read line; do [ ! -r "$line" ] && echo "Cannot Read $line"; done < filelist
-bash: filelist: Permission denied
What part of this is not working for you or not working as expected?
One possible explanation for why your error will not trigger is if you are running as root. You will have permission to read the file regardless of the permissions on the file:
# touch /tmp/foo
# chmod 200 /tmp/foo
# ls -l /tmp/foo
--w------- 1 root root 0 Dec 13 21:03 /tmp/foo
# test -r foo && echo readable
readable
From this, you can see that the file tests as "readable" even though there is no read permission set on the file.
精彩评论