[英]Is [ $var ] an acceptable way to check for variables set/empty in bash?
I wrote some bash before reading this popular question . 在阅读这个受欢迎的问题之前,我写了一些bash。 I noticed the way I was doing things doesn't show up in any of the answers so I was curious if there is a danger/bug to my logic that I am not seeing.
我注意到我的做事方式没有出现在任何答案中,所以我很好奇我的逻辑是否存在我看不到的危险/错误。
if [ ! $1 ] || [ $2 ]; then
echo "Usage: only one var." && exit 1
fi
As you can see, I am testing to see if there is one and only one parameter given on the command line. 如您所见,我正在测试以查看命令行上是否只有一个参数。 As far as I have tested, this works.
据我测试,这可行。 Can someone pass along some more knowledge to a new bash user?
有人可以将更多的知识传递给新的bash用户吗?
./script one '' oops
[ $2 ]
will be false when $2
is the empty string. 当
$2
为空字符串时, [ $2 ]
将为false。
And as that other guy points out in a comment, bash will split both strings, opening up a range of issues, including potential security holes. 正如其他人在评论中指出的那样,bash会拆分两个字符串,从而引发一系列问题,包括潜在的安全漏洞。
This is clearer: 这更清楚:
if [ $# != 1 ] ; then
echo "Usage: only one var."; exit 1
fi
Things that will break your test: 会破坏您的测试的事情:
""
) ""
) ""
) ""
) "bla bla"
) "bla bla"
) test
(eg: -z
) test
解释的内容(例如: -z
) It is simply less clearer than using $#
. 它根本没有使用
$#
更清晰。 Also the mere fact that I have to think about all the corner-cases which could potentially break the code makes it inferior. 同样,我不得不考虑所有可能破坏代码的极端情况这一事实也使它次等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.