How to check if a file is empty in Bash?

后端 未结 10 553
情书的邮戳
情书的邮戳 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 18:49

    Easiest way for checking file is empty or not:

    if [ -s /path-to-file/filename.txt ]
    then
         echo "File is not empty"
    else
         echo "File is empty"
    fi
    

    You can also write it on single line:

    [ -s /path-to-file/filename.txt ] && echo "File is not empty" || echo "File is empty"
    
    0 讨论(0)
  • 2020-11-30 18:52

    I came here looking for how to delete empty __init__.py files as they are implicit in Python 3.3+ and ended up using:

    find -depth '(' -type f  -name __init__.py ')' -print0 |
      while IFS= read -d '' -r file; do if [[ ! -s $file ]]; then rm $file; fi; done
    

    Also (at least in zsh) using $path as the variable also breaks your $PATH env and so it'll break your open shell. Anyway, thought I'd share!

    0 讨论(0)
  • 2020-11-30 18:59

    Misspellings are irritating, aren't they? Check your spelling of empty, but then also try this:

    #!/bin/bash -e
    
    if [ -s diff.txt ]
    then
            rm -f empty.txt
            touch full.txt
    else
            rm -f full.txt
            touch empty.txt
    fi
    

    I like shell scripting a lot, but one disadvantage of it is that the shell cannot help you when you misspell, whereas a compiler like your C++ compiler can help you.

    Notice incidentally that I have swapped the roles of empty.txt and full.txt, as @Matthias suggests.

    0 讨论(0)
  • 2020-11-30 19:02
    [[ -f filename && ! -s filename ]] && echo "filename exists and is empty"
    
    0 讨论(0)
  • 2020-11-30 19:06

    To check if file is empty or has only white spaces, you can use grep:

    if [[ -z $(grep '[^[:space:]]' $filename) ]] ; then
      echo "Empty file" 
      ...
    fi
    
    0 讨论(0)
  • 2020-11-30 19:07

    [[ -s file ]] --> Checks if file has size greater than 0

    if [[ -s diff.txt ]]; then echo "file has something"; else echo "file is empty"; fi
    

    If needed, this checks all the *.txt files in the current directory; and reports all the empty file:

    for file in *.txt; do if [[ ! -s $file ]]; then echo $file; fi; done
    
    0 讨论(0)
提交回复
热议问题