bash中的case语句,变量非空

huangapple go评论62阅读模式
英文:

bash case variable not empty

问题

I'm using a case statement like this in one of my projects to check some combinations of variables:

fun(){
    case "$a:$b:$c" in
          *:*:*) echo fine;;
          *:2:*) echo ok;;
          3:*:*) echo good;;
              *) echo not ok;;
    esac
}

The goal of the first case *:*:*) is to check that one of the vars, lets say $c is not empty. But it's not working like that, it's basically the same as *) at the end and triggers false positive if $c is not set. I've tried to use *:*:+ and *:*:!' ' no luck. So I've ended up using this:

fun(){
    c1=; [[ $c ]] && c1=1
    case "$a:$b:$c1" in
          *:*:1) echo fine;;
          *:2:*) echo ok;;
          3:*:*) echo good;;
              *) echo not ok;;
    esac
}

The question is - is there a better, more 'case' way?

英文:

I'm using a case statement like this in one of my projects to check some combinations of variables:

fun(){
    case "$a:$b:$c" in
          *:*:*) echo fine;;
          *:2:*) echo ok;;
          3:*:*) echo good;;
              *) echo not ok;;
    esac
}

The goal of the first case *:*:*) is to check that one of the vars, lets say $c is not empty. But it's not working like that, it's basically the same as *) at the end and triggers false positive if $c is not set. I've tried to use *:*:+ and *:*:!'' no luck. So I've ended up using this:

fun(){
    c1=; [[ $c ]] && c1=1
    case "$a:$b:$c1" in
          *:*:1) echo fine;;
          *:2:*) echo ok;;
          3:*:*) echo good;;
              *) echo not ok;;
    esac
}

The question is - is there a better, more 'case' way?

答案1

得分: 1

你可以简单地使用?通配符,它匹配一个字符。与?*结合使用时,这将匹配至少一个字符。

case "$a:$b:$c" in
    (*:*:?*) echo fine;;
    (*:2:?*) echo ok;;
    (3:*:?*) echo good;;
    (*) echo not ok;;
esac

我认为你应该改变备选项的顺序,因为例如 3:2:1 将会匹配到 fine,而没有三元组会匹配到 okgood

英文:

You can simply use the ? glob, which matches exactly one character. In combination with ?* this matches at least one character.

case "$a:$b:$c" in
     (*:*:?*) echo fine;;
     (*:2:?*) echo ok;;
     (3:*:?*) echo good;;
          (*) echo not ok;;
esac

I think you should change the order of the alternatives, since e.g. 3:2:1 will be fine and no triplet will ever be ok or good.

huangapple
  • 本文由 发表于 2023年6月8日 19:51:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76431577.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定