Check file size with test -s
In this step, you will learn how to check if a file exists and is not empty using the test
command with the -s
option. The test
command is a built-in shell command used to evaluate conditional expressions. It's often used in shell scripts to make decisions.
The -s
option with test
checks if a file exists and has a size greater than zero (i.e., it's not empty).
First, let's create an empty file and a non-empty file in your ~/project
directory.
Open your terminal if it's not already open. You should be in the ~/project
directory by default.
Create an empty file named empty_file.txt
:
touch empty_file.txt
Now, create a file named non_empty_file.txt
and add some text to it using the echo
command and the redirection operator >
. The >
operator redirects the output of a command to a file. If the file doesn't exist, it's created. If it exists, its contents are overwritten.
echo "This file has content." > non_empty_file.txt
Now, let's use the test -s
command to check these files. The test
command doesn't produce output on success. It signals success or failure using its exit status. An exit status of 0
means success (the condition is true), and a non-zero exit status means failure (the condition is false).
We can check the exit status of the previous command using the special variable $?
.
Check the empty file:
test -s empty_file.txt
echo $?
You should see the output 1
, indicating that the condition (file exists and is not empty) is false for empty_file.txt
.
Now, check the non-empty file:
test -s non_empty_file.txt
echo $?
You should see the output 0
, indicating that the condition is true for non_empty_file.txt
.
This is a fundamental way to check file properties in shell scripting. You can use this to ensure a file has content before attempting to process it.
Click Continue to proceed.