bash中的case语句,变量非空

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

bash case variable not empty

问题

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

  1. fun(){
  2. case "$a:$b:$c" in
  3. *:*:*) echo fine;;
  4. *:2:*) echo ok;;
  5. 3:*:*) echo good;;
  6. *) echo not ok;;
  7. esac
  8. }

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:

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

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:

  1. fun(){
  2. case "$a:$b:$c" in
  3. *:*:*) echo fine;;
  4. *:2:*) echo ok;;
  5. 3:*:*) echo good;;
  6. *) echo not ok;;
  7. esac
  8. }

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:

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

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

答案1

得分: 1

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

  1. case "$a:$b:$c" in
  2. (*:*:?*) echo fine;;
  3. (*:2:?*) echo ok;;
  4. (3:*:?*) echo good;;
  5. (*) echo not ok;;
  6. 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.

  1. case "$a:$b:$c" in
  2. (*:*:?*) echo fine;;
  3. (*:2:?*) echo ok;;
  4. (3:*:?*) echo good;;
  5. (*) echo not ok;;
  6. 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:

确定