Bash如果[-d $ 1]为空$ 1返回true [英] 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
..为什么在没有参数的情况下调用时会打印foo?对于空字符串,test [-d]如何返回true?
.. why does this print foo when called without arguments? How is it that the test [-d ] returns true for an empty string?
推荐答案
来自: info coreutils'test invocation'
(参考通过 man test
找到):
如果省略EXPRESSION,
test'返回false。 **如果EXPRESSION是
test'如果参数为null则返回false,否则返回true
单个参数,
**。参数可以是任何字符串,包括
-d',
-1',- ',$ c $等字符串c> - help'和
- 版本',大多数其他程序
[ - help'和`[ - version',没有通常的结束
将视为选项。要获取帮助和版本信息,请调用
命令
括号。
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.
正确突出显示:
如果EXPRESSION是单个参数,`如果
参数为null,则test'返回false,否则返回true
If EXPRESSION is a single argument, `test' returns false if the argument is null and true otherwise
所以每当我们做 [某事]
如果某事
不为空,它将返回 true
:
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
看到第二个 [ - d]&& echoyes
返回false,您可以解决此问题:引用 $ 1
以便 -d
总是得到一个参数:
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
这篇关于Bash如果[-d $ 1]为空$ 1返回true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!