While working with bash shell programming, when you need to read some file content. It is good to test that the given file exits or is not empty. This will safe your script from throwing errors. This article will help you to test if the file exists or not and the file is empty or not.
1. Check if File Empty or Not
This script will check if given file is empty or not. As per below example if /tmp/myfile.txt is an empty file then it will show output as “File empty”, else if file has some content it will show output as “File not empty”.
1 2 3 4 5 6 7 8 | #!/bin/bash if [ -s /tmp/myfile.txt ] then echo "File not empty" else echo "File empty" fi |
For the best practice, you can also write the above script in a single line as follows.
1 2 3 | #!/bin/bash [ -s /tmp/myfile.txt ] && echo "File not empty" || echo "File empty" |
2. Check if File Exists and Not Empty
The below script will check if the file exists and the file is empty or not. As per below example if /tmp/myfile.txt does not exist, script will show output as “File not exists” and if file exists and is an empty file then it will show output as “File exists but empty”, else if file exists has some content in it will show output as “File exists and not empty”.
1 2 3 4 5 6 7 8 9 10 11 | if [ -f /tmp/myfile.txt ] then if [ -s /tmp/myfile.txt ] then echo "File exists and not empty" else echo "File exists but empty" fi else echo "File not exists" fi |
3. Check if File Exists and Not Empty with Variable
This is the same as #2 except here file name is saved in a variable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #!/bin/bash FILENAME="/tmp/myfile.txt" if [ -f ${FILENAME} ] then if [ -s ${FILENAME} ] then echo "File exists and not empty" else echo "File exists but empty" fi else echo "File not exists" fi |
Rahul, great, short and sweet. Another website had a more involved approach to this, I always like the clear and concise approach.
what if file name variable is empty ?? Still it says File exists and not empty
#!/bin/bash
FILENAME=””
if [ -f ${FILENAME} ];then
if [ -s ${FILENAME} ]
then
echo “File exists and not empty”
else
echo “File exists but empty”
fi
else
echo “File not exists”
fi
Thanks Rahul, great post