EN
Bash - check if file is readable
3
points
In this article, we would like to show you how to check if file is readable using Bash.
Practical example
In this example, we use test command alias with -r option to check if file under the path is readable.
Example script.sh file:
#!/bin/bash
path="/path/to/file.txt"
if [ -r "$path" ]; then
echo "The file is readable."
fi
Note: this approach should be used in POSIX shells where other solutions may not work.
Run in command line:
./script.sh
Example output:
The file is readable.
Altermative notation
1. test based solution
#!/bin/bash
path="/path/to/file.txt"
if test -r "$path"; then
echo "The file is readable."
fi
Note:
[ ]notation is shorthand oftestcommand.
2. [[ ]] based solution
#!/bin/bash
path="/path/to/file.txt"
if [[ -r "$path" ]]; then
echo "The file is readable."
fi
Note:
[[ ]]notation is like extendedtestcommand, adding additional features (e.g. regular expressions).