Bash -S Test Condition
The test command with the -s flag allows you to check if files are empty or not in a Bash. If the file is not-empty, i.e. its value is greater than 0, it returns 0 as a true value. However, if the file is empty, it returns 1 as a false statement. To check if the file is empty or not in a Bash, we use the test command with the “-s” flag:
Under the Bash script, we will test whether the file named “LinuxHint” is empty:
test -s LinuxHint.txt
echo $?
Output:
Upon running the given script, you can see that 0 is returned in the output which means that the file is not empty.
Similarly, we will test the second file named “file.txt” and see if the file is empty or not:
test -s file.txt
echo $?
Output:
You can see that it returns 1 after running the previous file, so it is empty. Now, let’s use the -s test condition with the if statement to explain it better:
test -s LinuxHint.txt
If echo "LinuxHint.txt"
then
echo "File is not empty"
else
echo "File is empty"
fi
Output:
You can see that after running the previous Bash script, it tells you directly whether your file is empty or not.
Conclusion
In this tutorial, we explained the -s test condition in Bash. Through the -s flag, the test command displays whether the file is empty or not. Here, we tested two files using the Bash -s test condition to see if the files are empty or not. Bash is not limited to specific topics or segments. That’s why we uploaded a ton of guides on our website to give a complete Bash tutorial. Make sure you check them out!