在 bash 中检查空字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6665541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:21:19  来源:igfitidea点击:

Checking for null string in bash

linuxbash

提问by ?imon Tóth

Is there any difference between the following tests?

以下测试之间有什么区别吗?

[[ "$STRING" = "" ]] && exit 1;


[[ "x$STRING" = "x" ]] && exit 1;


[[ -z $STRING ]] && exit 1;

回答by Sodved

Nope, they are all the same. But couple of defensive habits to get into.

不,他们都是一样的。但是要养成一些防御习惯。

  • You should quote the $STRINGin the -zone as well
  • If you are running with the -u option (I always do) then you should reference the possibly optional variable as ${STRING-}just in case its not set at all
  • 你要引用$STRING-z一个,以及
  • 如果您使用 -u 选项运行(我总是这样做),那么您应该引用可能的可选变量,${STRING-}以防万一它根本没有设置

回答by Guilherme David da Costa

Apparently, they all do the same thing, that is check if the given string its "empty", except that the first one checks if $string its empty, the second checks whether x plus $string its equals to x and finally, -z that checks the length. Personally I'd ratter go with -z that's more realiable.

显然,他们都做同样的事情,即检查给定的字符串是否为“空”,除了第一个检查 $string 是否为空,第二个检查 x 加 $string 是否等于 x,最后,-z检查长度。我个人认为 -z 更可靠。