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

后端 未结 3 1773
时光取名叫无心
时光取名叫无心 2021-01-12 23:40

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

#!/bin/bash

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

.. why doe

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-13 00:02

    The reason that

    [ -d ] && echo y
    

    produces y is that the shell interprets it as a string in the test command and evaluates it to true. Even saying:

    [ a ] && echo y
    

    would produce y. Quoting from help test:

     string        True if string is not the null string.
    

    That is why quoting variables is recommended. Saying:

    [ -d "$1" ] && echo y
    

    should not produce y when called without arguments.

提交回复
热议问题