Reputation:
How do you test permissions on files using bash ? And how does it work ? Does it look for owner's permissions only or all of them (owner, group, others) ? I used -r and -w to test permissions on some files but I got some inaccurate responses.
Here is what I did :
[root@server1 ~]# cat script.sh
#!/bin/bash
FILE="$1"
[ $# -eq 0 ] && exit 1
if [[ -r "$FILE" && -w "$FILE" ]]
then
echo "We can read and write the $FILE"
else
echo "Access denied"
fi
[root@server1 ~]# ll file*
-rw-r--r--. 2 root root 1152 Jun 2 18:24 file1
-rwx------. 1 root root 3 Jun 6 20:35 file2
-r--------. 1 root root 3 Jun 6 20:35 file3
--w-------. 1 root root 3 Jun 6 20:35 file4
---x------. 1 root root 3 Jun 6 20:35 file5
----------. 1 root root 3 Jun 6 20:35 file6
[root@server1 ~]#
[root@server1 ~]# ./script.sh file1
We can read and write the file1
[root@server1 ~]# ./script.sh file2
We can read and write the file2
[root@server1 ~]# ./script.sh file3
We can read and write the file3
[root@server1 ~]# ./script.sh file4
We can read and write the file4
[root@server1 ~]# ./script.sh file5
We can read and write the file5
[root@server1 ~]# ./script.sh file6
We can read and write the file6
Thanks
Upvotes: 0
Views: 1352
Reputation: 1291
There is nothing essentially wrong with your script. You are executing it as root so you do have permission to read and write, in fact, root has permission to do anything!
Check this post and you will see that even suppressing the permissions, root user can have access to them. Your output is correct. If you look into the man page of the test command, you can see that the -r
and -w
flags test if the file exist and in addition permissions to read and write respectively are granted to the user executing the command (both of them since you use a logical and).
Upvotes: 1