我有一个叫diff。txt的文件。我想看看它是不是空的。
我写了一个bash脚本,类似于下面,但我不能让它工作。
if [ -s diff.txt ]
then
touch empty.txt
rm full.txt
else
touch full.txt
rm emtpy.txt
fi
我有一个叫diff。txt的文件。我想看看它是不是空的。
我写了一个bash脚本,类似于下面,但我不能让它工作。
if [ -s diff.txt ]
then
touch empty.txt
rm full.txt
else
touch full.txt
rm emtpy.txt
fi
当前回答
[[ -f filename && ! -s filename ]] && echo "filename exists and is empty"
其他回答
[-s file] #检查文件大小是否大于0
[ -s diff.txt ] && echo "file has something" || echo "file is empty"
如果需要,这将检查当前目录中的所有*.txt文件;并报告所有空文件:
for file in *.txt; do if [ ! -s $file ]; then echo $file; fi; done
[[ -f filename && ! -s filename ]] && echo "filename exists and is empty"
类似于@noam-manos的基于grep的答案,我用cat解决了这个问题。对我来说,-s不起作用,因为我的“空”文件有>0个字节。
if [[ ! -z $(cat diff.txt) ]] ; then
echo "diff.txt is not empty"
else
echo "diff.txt is empty"
fi
[ -s file.name ] || echo "file is empty"
检查文件是否为空的最简单的方法:
if [ -s /path-to-file/filename.txt ]
then
echo "File is not empty"
else
echo "File is empty"
fi
你也可以用单行写:
[ -s /path-to-file/filename.txt ] && echo "File is not empty" || echo "File is empty"