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.
In this example, we use test
command alias with -r
option to check if file under the path
is readable.
Example script.sh
file:
xxxxxxxxxx
1
2
3
path="/path/to/file.txt"
4
5
if [ -r "$path" ]; then
6
echo "The file is readable."
7
fi
Note: this approach should be used in POSIX shells where other solutions may not work.
Run in command line:
xxxxxxxxxx
1
./script.sh
Example output:
xxxxxxxxxx
1
The file is readable.
xxxxxxxxxx
1
2
3
path="/path/to/file.txt"
4
5
if test -r "$path"; then
6
echo "The file is readable."
7
fi
Note:
[ ]
notation is shorthand oftest
command.
xxxxxxxxxx
1
2
3
path="/path/to/file.txt"
4
5
if [[ -r "$path" ]]; then
6
echo "The file is readable."
7
fi
Note:
[[ ]]
notation is like extendedtest
command, adding additional features (e.g. regular expressions).