Bash Script to Check if File has Read Permissions
To check if the a file is readable, in other words if the file has read permissions, using bash scripting, use [ -r FILE ] expression with bash if statement.
Syntax
The syntax to check if the file is readable or not is given below.
[ -r FILE ]
where FILE represent path to the file whose permissions we need to check.
The expression returns a true if the file has read permission, and a false if the file does not have read permissions.
Following are the list of examples, that demonstrate us how to check if a file is readable or not.
- Example 1 – Simple if statement to check if file is readable
- Example 2 – Check if argument passed to function is a file and is readable
For the examples in this tutorial, we will use two files shown below:
$ ls -lr total 125016 --w------- 1 root root 12 Oct 5 09:35 sample.txt -rwxr--r-- 1 root root 20 Oct 5 15:33 dummy.txt
If you observe the permissions for these files,
- sample.txt has no read permissions.
- dummy.txt has read permissions for all users.
Example 1 – Check if File is Readable
In the following example, we shall use -r expression, and check if the file specified is readable. We use the expression in a bash if else statement.
Bash Script File
#!/bin/bash # Scenario - File exists and is readable if [ -r /home/tutorialkart/dummy.txt ]; then echo "/home/tutorialkart/dummy.txt is readable" else echo "/home/tutorialkart/dummy.txt is not readable" fi # Scenario - File exists and is not readable if [ -r /home/tutorialkart/sample.txt ]; then echo "/home/tutorialkart/sample.txt is readable" else echo "/home/tutorialkart/sample.txt is not readable" fi
Run this script file in a Terminal, and you shall see the following output, provided you have the files mentioned in your system.
Output
arjun@arjun-VPCEH26EN:~/workspace/bash$ ./bash-script-if-file-is-readable /home/tutorialkart/dummy.txt is readable /home/tutorialkart/sample.txt is not readable
Example 2 – Write a Function that Checks If File is Readable
In this example, we shall write a function whose first argument is path to a file. And in the function we shall check if the passed argument (FILE) is readable or not.
Bash Script File
#!/bin/bash # function to check if passed argument is readable checkIfReadable() { # $1 meaning first argument if [ -r "$1" ]; then echo "$1 is readable." else echo "$1 is not readable." fi } # Scenario - File exists and is readable checkIfReadable "/home/tutorialkart/dummy.txt" # Scenario - File exists and is not readable checkIfReadable "/home/tutorialkart/sample.txt"
Run the above script and you will get the following output.
Output
arjun@arjun-VPCEH26EN:~/workspace/bash$ ./bash-script-if-file-is-readable-2 /home/tutorialkart/dummy.txt is readable. /home/tutorialkart/sample.txt is not readable.
Conclusion
In this Bash Tutorial, we have learnt how to check if the specified file has read permissions or not.