Search code examples
linuxbashshellswitch-statementglob

bash case glob in order to match part of hostname and ignore last characters


we tested the following script - script.sh on machine hostname - presto-data1-01 , but seems the regex presto-data+([[:digit:]]) isn't good enough

machines hosts are as example:

presto-data1-01
presto-data1-02
presto-data1-03

or

presto-data2-01
presto-data2-02
presto-data2-03

etc

my script and example

more /tmp/script.sh

#!/usr/bin/env bash
hostname=$(hostname -s)


shopt -s extglob


case $hostname in

        presto+([[:digit:]]))
          bash /home/presto.sh;;

        presto-data+([[:digit:]]))
          bash /home/presto-data.sh;;
        *)  echo "Unrecognized hostname $hostname" ;;
esac


bash  /tmp/script.sh
Unrecognized hostname presto-data1-01

my machine name :

[root@presto-data1-01 # hostname -s
presto-data1-01

what we need to fix in regex - presto-data+([[:digit:]]) , in order to match as example the presto-data1 and ignore the characters after presto-data1 as "-01"


Solution

  • Use * to ignore last characters

    #!/usr/bin/env bash
    hostname=$(hostname -s)
    
    
    shopt -s extglob
    
    
    case $hostname in
    
            presto+([[:digit:]])*)
              bash /home/presto.sh;;
    
            presto-data+([[:digit:]])*)
              bash /home/presto-data.sh;;
            *)  echo "Unrecognized hostname $hostname" ;;
    esac