null values in bash scripts always true?
In a shell script I am testing to see if a string passed to it is a file or a directory using the -f and -d oprerators something like this:
Code:
if [ -d $1 ] ; then Why does bash think that an empty string is a directory or a file. It should be neither! Does bash always evaluate a null value as true? Is that behavior common to all or most programming languages? - Joe |
It's actually not bash that says whether the argument is a directory or not: it's test
The open square bracket is an alias for a separate system utility named test. That program is responsible for determining if an expression is true or false. If you wanted to verify, you can execute the same commands from the prompt: Code:
$ test -d To answer your question though, normally null values and 0 are considered false in programming languages. So there is a little disagreement among shell/programming. |
The fix to get around this problem would be to check for zero sized STRING.
$ man test Code:
if [ -z $1 ] ; then |
Quote:
Code:
if [ -d "$1" ] |
Thank you eddiebaby. Quoting the varaible turns a null to an empty string and then I get the results I expected.
And a thank you to dark_helmet for pointing out "test". - Joe |
It doesn't actually turn it into an empty string - it's that already. What the shell does is preserve it in place so the command can see it.
|
All times are GMT -5. The time now is 10:00 AM. |