Is Readable Check In Bash
Using [[ -r file ]]
is a good way to check if a file exists and is readable in Bash. However, whether itβs the best way depends on your specific requirements.
β
When to Use [[ -r file ]]
- When you want to ensure the file both exists and is readable by the current user.
- In most bash environments,
[[ ]]
is preferred over[ ]
due to better syntax, built-in support for pattern matching, and fewer surprises with quoting.
if [[ -r "$file" ]]; then
echo "File exists and is readable"
else
echo "File is missing or not readable"
fi
π Other Common File Check Options
Option | Purpose |
---|---|
[[ -e file ]] | Check if the file exists (but doesnβt check readability). |
[[ -f file ]] | Check if itβs a regular file (not directory, socket, etc.). |
[[ -w file ]] | Check if it exists and is writable by the user. |
[[ -x file ]] | Check if it exists and is executable. |
π‘ Alternative and Why It May Be Better
If you care more about readability success when opening the file rather than just checking permissions, try actually opening the file instead of relying on -r
:
if exec 3< "$file"; then
echo "File is readable"
exec 3<&-
else
echo "File is not readable"
fi
Why? Because -r
only checks permissions but doesnβt account for cases where the user may have permissions but still fails to read (e.g., filesystem-level issues).
π¨ Common Pitfalls
- Symbolic links:
-r
checks permissions on the target, not the link itself. - Directories:
-r
will return true for readable directories too. - Setuid/setgid: May not reflect actual access if elevated privileges are involved.
π Recommendation
- For basic "does it exist and can I read it?" checks,
[[ -r ]]
is usually sufficient and preferred. - If robustness matters (e.g., for production scripts), use file opening (
exec
) to test actual readability. - Always ensure variables are quoted to avoid filename issues (
"$file"
).
Backlinks