英文:
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
,而没有三元组会匹配到 ok
或 good
。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论