linuxbashcaselookuphostname

How can I cleanly do a lookup of a value with a substring extracted from a hostname in bash?


the following bash regex will set the memory variable according to machine hostname name

we have in the lab many machines with different name as following small example

presto01
presto02

hadoop01
hadoop02

mngmnthadoop01
mngmnthadoop01
.
.
.

for example if hostname - is contain the presto name or mngmntpresto name , then following bash code will set the variable memory to 23G

hostname=$( hostname -s )

[[ $hostname =~ (^|^mngmnt)presto[[:digit:]]+$ ]] && memory=23G
        
[[ $hostname =~ (^|^mngmnt)hadoop[[:digit:]]+$ ]] && memory=12G
        
[[ $hostname =~ (^|^mngmnt)kafka[[:digit:]]+$ ]] && memory=10G
.
.
.
    

but as I know case in bash not support regular expressions but doing my code as I explained isn't so elegant , and I am wondering if we can do it better ?


Solution

  • You could use a case statement with extended globbing patterns:

    shopt -s extglob
    case $hostname in
        ?(mngmnt)presto+([[:digit:]]) ) memory=23G;;
        ?(mngmnt)hadoop+([[:digit:]]) ) memory=12G;;
        ?(mngmnt)kafka+([[:digit:]])  ) memory=10G;;
        *) printf 'ERROR: Unrecognized hostname: %s\n' "$hostname" >&2;;
    esac