我有一个叫diff。txt的文件。我想看看它是不是空的。

我写了一个bash脚本,类似于下面,但我不能让它工作。

if [ -s diff.txt ]
then
        touch empty.txt
        rm full.txt
else
        touch full.txt
        rm emtpy.txt
fi

当前回答

拼写错误很烦人,不是吗?检查一下empty的拼写,然后试试这个:

#!/bin/bash -e

if [ -s diff.txt ]; then
        # The file is not-empty.
        rm -f empty.txt
        touch full.txt
else
        # The file is empty.
        rm -f full.txt
        touch empty.txt
fi

我非常喜欢shell脚本,但它的一个缺点是,当你拼写错误时,shell不能帮助你,而像c++编译器这样的编译器可以帮助你。

顺便注意一下,我交换了empty.txt和full.txt的角色,就像@Matthias建议的那样。

其他回答

拼写错误很烦人,不是吗?检查一下empty的拼写,然后试试这个:

#!/bin/bash -e

if [ -s diff.txt ]; then
        # The file is not-empty.
        rm -f empty.txt
        touch full.txt
else
        # The file is empty.
        rm -f full.txt
        touch empty.txt
fi

我非常喜欢shell脚本,但它的一个缺点是,当你拼写错误时,shell不能帮助你,而像c++编译器这样的编译器可以帮助你。

顺便注意一下,我交换了empty.txt和full.txt的角色,就像@Matthias建议的那样。

[-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

要检查文件是否为空或只有空格,可以使用grep:

if [[ -z $(grep '[^[:space:]]' $filename) ]] ; then
  echo "Empty file" 
  ...
fi

@geedoubleya的答案是我最喜欢的。

然而,我更喜欢这样

if [[ -f diff.txt && -s diff.txt ]]
then
  rm -f empty.txt
  touch full.txt
elif [[ -f diff.txt && ! -s diff.txt ]]
then
  rm -f full.txt
  touch empty.txt
else
  echo "File diff.txt does not exist"
fi

类似于@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