Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script to test if a given user can read a directory and all files inside?

I need to test in a bash script if a given user can read a given directory with all files and sub-directories inside. The script runs as root.

Assuming the given user name is $user and the directory to test is $dir I added the following line to the script

su -m $user -c "test -r $dir && test -x $dir"
if [ $? -ne ]; then
   echo "$dir is not readable or executable"
fi

Would you suggest correct or improve it?

like image 693
Michael Avatar asked Oct 24 '13 14:10

Michael


People also ask

How do you check if there are files in a directory bash?

In order to check if a file exists in Bash using shorter forms, specify the “-f” option in brackets and append the command that you want to run if it succeeds. [[ -f <file> ]] && echo "This file exists!" [ -f <file> ] && echo "This file exists!" [[ -f /etc/passwd ]] && echo "This file exists!"

How can I tell if a directory is readable?

canRead() is used to check if a file or directory is readable in Java. This method returns true if the file specified by the abstract path name can be read by an application and false otherwise.


1 Answers

You could simply say:

su -m $user -c "find $dir >/dev/null 2>&1 || echo $dir is not readable or executable"

This would generate the not readable or executable message if any files/directories within $dir are not readable.

find $dir would return an error code of non-zero if it's not able to read any file.


EDIT: A more complete (or reliable) way of finding all directories/files that are not readable would be to say:

find . \( -type d -perm /u+r -o -type d -perm /u+x -o -type f -perm /u+r \)
like image 121
devnull Avatar answered Sep 23 '22 23:09

devnull