Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If file is exists and is not empty. Always gives me the false value

I have a bash script:

echo " enter file name " read $file if [ -f "$file" ] && [ -s "$file" ] then     echo " file does not exist, or is empty " else    echo " file exists and is not empty " fi 

No matter what I enter as a $file, it gives me the false value. I can even enter a file that does not even exist; it still will give me the false value. Why is that?

like image 223
demboz11 Avatar asked May 06 '15 15:05

demboz11


People also ask

How do you check if a file exists or not empty?

You can use the find command and other options as follows. The -s option to the test builtin check to see if FILE exists and has a size greater than zero. It returns true and false values to indicate that file is empty or has some data.

Which of the below would you use to check if a file exists and is not empty?

Please note, that [ -f "$file" ] && [ -s "$file" ] will return true if file exists and is not empty.

Which command correct file if file does not exist?

To test if a file does not exist using the “||” operator, simply check if it exists using the “-f” flag and specify the command to run if it fails. [[ -f <file> ]] || echo "This file does not exist!"


1 Answers

It is enough to check for -s, because it says:

FILE exists and has a size greater than zero

http://unixhelp.ed.ac.uk/CGI/man-cgi?test

also your output is switched, so it outputs does not exists when a file exists, because -s will give TRUE if file exists AND has a size > 0.

So correctly you should use:

echo " enter file name " read file if [ -s "$file" ] then     echo " file exists and is not empty " else    echo " file does not exist, or is empty " fi 

This will give you the expected output.

Also it should be

read file 

instead of

read $file 

If you want further informations, I recommand reading man test and man read

like image 193
Nidhoegger Avatar answered Sep 29 '22 09:09

Nidhoegger