简体   繁体   English

[$ var]是检查bash中变量设置/空的可接受方法吗?

[英]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: 会破坏您的测试的事情:

  • The first parameter is empty ( "" ) 第一个参数为空( ""
  • The second parameter is empty ( "" ) 第二个参数为空( ""
  • The first or second parameter has more words ( "bla bla" ) 第一个或第二个参数包含更多单词( "bla bla"
  • The parameters contain something that will be interpreted by 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM