在 bash if 语句中使用通配符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19354024/
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 08:17:31  来源:igfitidea点击:

Using wildcards in bash if statement

bashshellsh

提问by Rami Chaouki

I wrote the following code in the bash shell. It's supposed to take the positional parameter, and if it starts with a dash "-", it's supposed to input an error message.

我在 bash shell 中编写了以下代码。它应该采用位置参数,如果它以破折号“-”开头,则应该输入错误消息。

But for some reason, the if statement always gets skipped. It only functions if I literally input -*

但出于某种原因,if 语句总是被跳过。只有当我从字面上输入 -* 时它才起作用

I get the impression that the fix has something to do with the "$".

我的印象是修复与“$”有关。

Here is a snippet of the code:

这是代码的一个片段:

    EXECNAME=
    if [ "$EXECNAME" = "-*" ]; then
           echo "error: invalid executable name"
    fi

回答by anubhava

You can use double square brackets [[and ]]without use of quotes on matching pattern for glob support in BASH:

您可以使用双括号[[,并]]没有使用上的BASH水珠支持匹配模式的报价:

[[ "$EXECNAME" = -* ]] && echo "error: invalid executable name"

回答by holygeek

For matching against glob pattern I prefer to use case:

为了匹配 glob 模式,我更喜欢使用case

case $EXECNAME in
  -*) echo "error: invalid executable name"
esac