How to check if a file is empty in Bash?

后端 未结 10 657
情书的邮戳
情书的邮戳 2020-11-30 18:41

I have a file called diff.txt. I Want to check whether it is empty.

I wrote a bash script something like below, but I couldn\'t get it work.

10条回答
  •  野性不改
    2020-11-30 19:08

    While the other answers are correct, using the "-s" option will also show the file is empty even if the file does not exist.
    By adding this additional check "-f" to see if the file exists first, we ensure the result is correct.

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

提交回复
热议问题