Search code examples
linuxbashunixfile-handlingis-empty

How to check if a file is empty in Bash?


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.

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

Solution

  • try this:

    #!/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
    

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