Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between -f and -s options in If condition?

What is the difference between -f and -s Option in If condition

Mainly how they are different in functionality?

I know the google meaning of these but want to know the practical use.

like image 686
user2968521 Avatar asked Oct 26 '25 14:10

user2968521


1 Answers

From man test:

-f FILE
          FILE exists and is a regular file

-s FILE
          FILE exists and has a size greater than zero

Example

Let's create a file from scratch and check it out.

$ touch b

Does the file exist?

$ [ -f "b" ] && echo "file exists"
file exists                          # yes!!!!

Does the file have a size greater than zero?

$ [ -s "b" ] && echo "file exists and is greater than zero"
$                                    # no!!!!

So a good if-elif-else condition to check the existence of a file could be:

if [ -s "$file" ]; then
   echo "exists and it is not empty"
elif [ -f "$file" ]; then
   echo "at least exists"
else
   echo "does not exist"
fi
like image 192
fedorqui 'SO stop harming' Avatar answered Oct 28 '25 03:10

fedorqui 'SO stop harming'



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!