Test readability with test -r
In this step, you will learn how to check if you have read permission for a file using the test
command with the -r
option.
The test
command is a built-in shell command that evaluates conditional expressions. It's often used in shell scripts to make decisions. The -r
option specifically checks if a file exists and is readable by the current user.
Let's create a simple file to test this. We'll use the echo
command to put some text into a file named my_file.txt
in your ~/project
directory.
Type the following command and press Enter:
echo "This is a test file." > ~/project/my_file.txt
This command creates the file ~/project/my_file.txt
and writes the string "This is a test file." into it. The >
symbol redirects the output of the echo
command to the specified file.
Now, let's use test -r
to check if you can read this file. The test
command itself doesn't produce output if the condition is true. We usually combine it with other commands like echo
to see the result.
Type the following command and press Enter:
test -r ~/project/my_file.txt && echo "File is readable."
The &&
operator means "execute the command on the right only if the command on the left succeeds (returns a zero exit status)". If test -r ~/project/my_file.txt
is true (meaning the file is readable), the echo
command will execute.
You should see the output:
File is readable.
Now, let's try checking a file that doesn't exist.
Type the following command and press Enter:
test -r ~/project/non_existent_file.txt && echo "This won't be printed."
Since ~/project/non_existent_file.txt
does not exist, test -r
will return a non-zero exit status (failure), and the echo
command will not be executed. You should see no output from this command.
The test
command is a fundamental tool for scripting in Linux. Understanding how to use its various options, like -r
, is crucial for writing robust scripts that can check for file permissions and existence before attempting operations.
Click Continue to proceed to the next step.