user7355683
user7355683

Reputation:

Trouble with Case Command in bash

I want to match a string that follows this pattern:

It should start with an a A, K, N or W then can be followed by a digit or letters in the range a-zA-Z, and if it has a letter as the second letter a digit follows it and then it can have 1, 2 or 3 letters.

I tried this:

#!/bin/bash
function callsign() {
    echo -e "Insert your call sign"
    while true; do
    read input
    case $input in
        [Aa,Kk,Nn,Ww][0-9][a-zA-Z][a-zA-Z] ) break;;
        [Aa,Kk,Nn,Ww][a-zA-Z][0-9][a-zA-Z] ) break;;
        [Aa,Kk,Nn,Ww][a-zA-Z][0-9][a-zA-Z][a-zA-Z] ) break;;
        [Aa,Kk,Nn,Ww][0-9][a-zA-Z][a-zA-Z][a-zA-Z] ) break;;
        [Aa,Kk,Nn,Ww][0-9][a-zA-Z][a-zA-Z][a-zA-Z][a-zA-Z] ) break ;;
        * ) echo "please insert valid call sign.";;
    esac
    done
    clear
}
callsign

I'm having problems because I have too many cases (and yet not including them all). How can I solve this in a better way?

Upvotes: 1

Views: 56

Answers (1)

gniourf_gniourf
gniourf_gniourf

Reputation: 46813

So I should start With an Any A K N W then can be followed by a Number or Letters a-z and if it Has a letter as the second letter a number follows it and then it can have 1-3 letters

There are several possibilities to do the match. One of them is to use a regex:

#!/bin/bash

shopt -s nocasematch

callsign() {
   while true; do
      read -ep "Insert your call sign: " input
      if [[ $input =~ [aknw](|[a-z])[0-9][a-z](|[a-z](|[a-z])) ]]; then
         break
      else
         echo "please insert valid call sign."
      fi
   done
   echo "it works!"
}
callsign

Another possibility is to use an extended glob:

#!/bin/bash

shopt -s nocasematch extglob

callsign() {
   while true; do
      read -ep "Insert your call sign: " input
      if [[ $input = [aknw]@(|[a-z])[0-9][a-z]@(|[a-z]@(|[a-z])) ]]; then
         break
      else
         echo "please insert valid call sign."
      fi
   done
   echo "it works!"
}
callsign

Note the use of nocasematch so that it deals with lower/uppercase.

Upvotes: 1

Related Questions