I know [ -f file ]
, if we use it as a conditional check, checks if file is an ordinary file as opposed to a directory or special file; if yes, then the condition becomes true.
Also I Know [ -e file ]
Checks if file exists; is true even if file is a directory.
Let's say I have some code as below (saved as test.sh
) for checking if its a regular file:
#!/bin/bash
file=$1
if [ -e $file ]
then
echo "file exists"
if [ -f $file ]
then
echo "It's a regular file"
else
echo "It's not a regular file"
fi
else
echo "file doesn't exist"
fi
And I am running is as below:
./test.sh /etc/passwd
My output is as expected as below:
file exists
Its a regular file
And If I pass a invalid file or directory as argument:
./test.sh dsdsafds
Still the output is as expected:
file doesn't exist
But if I am running the script without any argument, (meaning $1
will be null):
./test.sh
Both the if
conditions are getting satisfied and my output is:
file exists
Its a regular file
Why is it so? Even though $1
is null, how can [ -e file ]
and [ -f file ]
be true?
And is there any way if I can output/print the Boolean values returned by such test operators?