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?
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.
Please note, that [ -f "$file" ] && [ -s "$file" ] will return true if file exists and is not empty.
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!"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With