How to check if a file is empty in Bash?

后端 未结 10 617
情书的邮戳
情书的邮戳 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
    
    0 讨论(0)
  • 2020-11-30 19:12

    Many of the answers are correct but I feel like they could be more complete / simplistic etc. for example :

    Example 1 : Basic if statement

    # BASH4+ example on Linux :
    
    typeset read_file="/tmp/some-file.txt"
    if [ ! -s "${read_file}" ]  || [ ! -f "${read_file}" ] ;then
        echo "Error: file (${read_file}) not found.. "
        exit 7
    fi
    

    if $read_file is empty or not there stop the show with exit. More than once I have had misread the top answer here to mean the opposite.

    Example 2 : As a function

    # -- Check if file is missing /or empty --
    # Globals: None
    # Arguments: file name
    # Returns: Bool
    # --
    is_file_empty_or_missing() {
        [[ ! -f "${1}" || ! -s "${1}" ]] && return 0 || return 1
    }
    
    0 讨论(0)
  • 2020-11-30 19:13
    [ -s file.name ] || echo "file is empty"
    
    0 讨论(0)
  • 2020-11-30 19:14

    @geedoubleya answer is my favorite.

    However, I do prefer this

    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
    
    0 讨论(0)
提交回复
热议问题