Bash Script – Check if file has read permissions
To check if a file is readable in bash, in other words if the file has read permissions, use [ -r FILE ] expression.
Syntax
The syntax of the expression to check if the file is readable or not is given below.
[ -r path/to/file ]
replace path/to/file
with the actual path to file, whose read permissions you need to check.
The expression returns a value of true if the file is present and has read permission, or a false if the file does not have read permissions.
Examples
For the sake of examples, 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.
1. Check if file is readable for dummy.txt
In the following example, we shall use -r
expression, and check if the file dummy.txt
is readable. We use the -r
option as a condition in bash if else statement.
example.sh
#!/bin/bash
file="dummy.txt"
if [ -r "$file" ]
then
echo "$file is readable."
else
echo "$file is not readable."
fi
Bash Version: GNU bash, version 5.2.15(1)-release (aarch64-apple-darwin22.1.0)
Run this script file in a Terminal, and you shall see the following output, provided you have the file dummy.txt mentioned in your system.
Output
sh-3.2# bash example.sh
dummy.txt is readable.
2. Check if file is readable for sample.txt
In the following example, we shall use -r
expression, and check if the file sample.txt
is readable.
example.sh
#!/bin/bash
file="sample.txt"
if [ -r "$file" ]
then
echo "$file is readable."
else
echo "$file is not readable."
fi
Bash Version: GNU bash, version 5.2.15(1)-release (aarch64-apple-darwin22.1.0)
Output
sh-3.2# bash example.sh
sample.txt is not readable.
Conclusion
In this Bash Tutorial, we learned how to check if specified file is readable or not.