ziga
ziga

Reputation: 109

Behaviour of "-s" option with "test" command in bash script

The code is:

src=/home/Desktop/src
dest=/home/Desktop/dest

if test -s $src/$InputFile ; then
  echo "File is present. :$InputFile" 
else
  echo "File is not present" 
fi

In the above code if I declare variable "InputFile" as InputFile=a.txt then it goes and check for a file a.txt in src directory, if file exists it prints "File is present". If file does not exists then it prints "File is not present".

I have not declared variable "InputFile" in above code. Still it goes to src path and execute if condition and prints "File is present". Can anyone tell me exact behaviour of "test -s" when filename variable is empty?

Upvotes: 0

Views: 3080

Answers (2)

Ipor Sircer
Ipor Sircer

Reputation: 3141

You ran:

test -s /home/Desktop/src/

And this /home/Desktop/src/ is not an empty directory.

Upvotes: 2

heemayl
heemayl

Reputation: 42097

The misunderstanding arises from the fact that -s works not only on regular files, but on all kinds of files.

So when you make the InputFile variable null, it is checking the existence and size of the directory expanded from $src, and returning $? as 0 as the directory occupies a minimum of block-sized size on the filesystem (assuming the directory exists at the first place).

Upvotes: 0

Related Questions