Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash if [ -d $1] returning true for empty $1

So I have the following little script and keep wondering..

#!/bin/bash

if [ -d $1 ]; then
  echo 'foo'
else
  echo 'bar'
fi

.. why does this print foo when called without arguments? How is it that the test [-d ] returns true for an empty string?

like image 547
fgysin Avatar asked Feb 10 '14 13:02

fgysin


1 Answers

From: info coreutils 'test invocation' (reference found through man test):

If EXPRESSION is omitted, test' returns false. **If EXPRESSION is a single argument,test' returns false if the argument is null and true otherwise**. The argument can be any string, including strings like -d',-1', --',--help', and --version' that most other programs would treat as options. To get help and version information, invoke the commands[ --help' and `[ --version', without the usual closing brackets.

Highlighting properly:

If EXPRESSION is a single argument, `test' returns false if the argument is null and true otherwise

So whenever we do [ something ] it will return true if that something is not null:

$ [ -d ] && echo "yes"
yes
$ [ -d "" ] && echo "yes"
$ 
$ [ -f  ] && echo "yes"
yes
$ [ t ] && echo "yes"
yes

Seeing the second one [ -d "" ] && echo "yes" returning false, you get the way to solve this issue: quote $1 so that -d always gets a parameter:

if [ -d "$1" ]; then
  echo 'foo'
else
  echo 'bar'
fi
like image 135
fedorqui 'SO stop harming' Avatar answered Oct 02 '22 06:10

fedorqui 'SO stop harming'