Bash Script – Check if file has read permissions
To check if a file is writable in bash, in other words if the file has write permissions for current user, use -w
option.
The syntax of the boolean expression to check if a file is writeable or not is given below.
[ -w path/to/file ]
replace path/to/file
with the actual path to file, whose write permissions you need to check.
The expression returns a value of true if the file is present and has write permission for current user, or a false if the file does not have write permissions.
Examples
For the sake of examples, we check the write permissions of two files shown below.
sh-3.2# ls -lr
total 32
-rw-rw-rw-@ 1 tutorialkart staff 42 Feb 4 16:55 sample.txt
-rwxrwxrwx@ 1 tutorialkart staff 136 Feb 5 07:51 example.sh
-r--r--r-- 1 tutorialkart staff 0 Feb 4 17:24 data.txt
If you observe the permissions for these files,
- sample.txt has write permissions for all users.
- data.txt has only read permissions, but no write permissions.
1. Check if File is Writable – sample.txt
In the following example, we shall use -w
option to check if the file sample.txt
is writable.
Bash Script File
#!/bin/bash
filename="sample.txt"
if [ -w "$filename" ];
then
echo "$filename is writable."
else
echo "$filename is not writable."
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 files mentioned in your system with the same permissions.
Output
2. Check if File is Writable – data.txt
In the following example, we shall use -w
option to check if the file data.txt
is writable. Since data.txt
has no right permissions, else block must execute.
Bash Script File
#!/bin/bash
file="data.txt"
if [ -w "$file" ]
then
echo "$file is writable."
else
echo "$file is not writable."
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 data.txt
with the same permissions mentioned above.
Output
sh-3.2# bash example.sh
data.txt is not writable.
Conclusion
In this Bash Tutorial, we learned how to check if specified file is writable or not.