Check file existence using the test command
In this step, you will learn how to check if a file exists in Linux using the test
command. The test
command is a built-in shell command that evaluates conditional expressions. It's often used in shell scripts to make decisions based on the existence or properties of files and directories.
First, let's create a simple file in your current directory (~/project
). We'll use the echo
command to put some text into a file named my_file.txt
.
Type the following command and press Enter:
echo "This is a test file." > my_file.txt
This command creates a file named my_file.txt
in your current directory (~/project
) and writes the text "This is a test file." into it. The >
symbol redirects the output of the echo
command to the specified file.
Now, let's use the test
command to check if my_file.txt
exists. The -f
option with test
checks if a file exists and is a regular file.
Type the following command and press Enter:
test -f my_file.txt
The test
command doesn't produce any output if the condition is true (the file exists). If the file did not exist, it would return a non-zero exit status, which is typically used in scripting.
To see the result of the test
command, you can check the exit status of the previous command using echo $?
. An exit status of 0
means the command was successful (the condition was true), and a non-zero exit status means it failed (the condition was false).
Type the following command and press Enter:
echo $?
You should see the output 0
, indicating that the test -f my_file.txt
command was successful because the file exists.
Now, let's try checking for a file that doesn't exist, like non_existent_file.txt
.
Type the following command and press Enter:
test -f non_existent_file.txt
Again, test
won't produce output if the condition is false. Let's check the exit status:
echo $?
This time, you should see an output of 1
(or another non-zero number), indicating that the test -f non_existent_file.txt
command failed because the file does not exist.
Understanding the test
command and checking exit statuses is fundamental for writing shell scripts that can make decisions based on the file system.
Click Continue to proceed to the next step.