Bash Script to Check if File Exists and Is Readable
if [ -r filename ] in Bash to check if a file exists and is readable; it returns true only if the file exists and you have read permission.Examples
How to Think About It
-r test operator checks both at once, so you only need to test that condition to confirm both existence and readability.Algorithm
Code
#!/bin/bash filename="$1" if [ -r "$filename" ]; then echo "File '$filename' exists and is readable." else echo "File '$filename' does not exist or is not readable." fi
Dry Run
Let's trace checking 'file.txt' that exists and is readable through the code
Set filename variable
filename='file.txt'
Check if file is readable
[ -r 'file.txt' ] returns true
Print success message
echo "File 'file.txt' exists and is readable."
| Step | Condition | Result |
|---|---|---|
| Check -r 'file.txt' | File exists and readable | true |
| Print message | N/A | File 'file.txt' exists and is readable. |
Why This Works
Step 1: Using -r test operator
The -r operator checks if the file exists and if the current user has read permission on it.
Step 2: Conditional branching
The if statement runs the test and executes the first block if true, otherwise the else block.
Step 3: Output message
The script prints a clear message telling if the file is accessible or not.
Alternative Approaches
#!/bin/bash filename="$1" if [ -e "$filename" ] && [ -r "$filename" ]; then echo "File '$filename' exists and is readable." else echo "File '$filename' does not exist or is not readable." fi
#!/bin/bash filename="$1" test -r "$filename" && echo "File '$filename' exists and is readable." || echo "File '$filename' does not exist or is not readable."
Complexity: O(1) time, O(1) space
Time Complexity
Checking file existence and permissions is a constant-time operation handled by the OS, so it runs in O(1) time.
Space Complexity
The script uses a fixed amount of memory for variables and commands, so space complexity is O(1).
Which Approach is Fastest?
All approaches use simple OS checks and run in constant time; the difference is mainly readability and style.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Single -r test | O(1) | O(1) | Simple and concise checks |
| Separate -e and -r tests | O(1) | O(1) | Clearer intent, more verbose |
| test command with && || | O(1) | O(1) | Compact one-liner scripts |