Search code examples
regexbashcase

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?


Solution

  • 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.