You can use the find command as follows. The -s option to the test builtin check to see if FILE exists and has a size greater than zero. It returns true and false values to indicate that file is empty or has some data.
touch /tmp/file1Sample outputs:
ls -l /tmp/file1
find /tmp -empty -name file1
/tmp/file1Now create another file with some data in it:
echo "data" > /tmp/file2You should not see any output.
ls -l /tmp/file2
find /tmp -empty -name file2
Shell -s option
However, use can pass -s option as follows in script or shell prompt:touch /tmp/f1Sample outputs:
echo "data" >/tmp/f2
ls -l /tmp/f{1,2}
[ -s /tmp/f1 ]
echo $?
1The non zero output indicate that file is empty.
[ -s /tmp/f2 ]Sample outputs:
echo $?
0The zero output indicate that file is not empty. So you can write a shell script as follows:
Shell Script To Check If File Is Empty OR Not
#!/bin/bashRun it as follows:
_file="$1"
[ $# -eq 0 ] && { echo "Usage: $0 filename"; exit 1; }
[ ! -f "$_file" ] && { echo "Error: $0 file not found."; exit 2; }
if [ -s "$_file" ]
then
echo "$_file has some data."
# do something as file has data
else
echo "$_file is empty."
# do something as file is empty
fi
chmod +x script.sh
./script.sh /etc/resolv.conf
Sample outputs:
/etc/resolv.conf has some data.Run it on an empty file:
touch /tmp/test.txt
./script.sh /tmp/test.txt
Sample outputs:
test.txt is empty.
No comments:
Post a Comment