check if a file is empty in shell script
A shell script (isEmpty.sh) example to check if a file is empty or not.
[code language=”shell”]
#!/bin/sh
f=’afile.txt’
hasData ()
{
echo "$f has data."
ls -l $f
cat $f
}
noData()
{
echo "$f is empty."
ls -l $f
}
if [[ -s $f ]]
then
hasData
else
noData
fi
[/code]
The text file afile.txt
[code language=”shell”]
hello world
[/code]
The output when the file has data
[code language=”shell”]
afile.txt has data.
-rw-r–r–+ 1 username 941854322 12 Jan 17 11:31 afile.txt
hello world
[/code]
The output when the file is empty.
[code language=”shell”]
afile.txt is empty.
-rw-r–r–+ 1 username 941854322 0 Jan 17 11:37 afile.txt
[/code]
The run the script.
[code language=”shell”]
chmod +x isEmpty.sh
./isEmpty.sh
[/code]
Search within Codexpedia
Search the entire web