Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expressions in a Bash case statement

I am using following script, which uses case statement to find the server.

    #!/bin/bash SERVER=$1; echo $SERVER | egrep "ws-[0-9]+\.host\.com"; case $SERVER in ws-[0-9]+\.host\.com) echo "Web Server" ;; db-[0-9]+\.host\.com) echo "DB server" ;; bk-[0-9]+\.host\.com) echo "Backup server" ;; *)echo "Unknown server" ;; esac 

But it is not working. Regex is working with egrep but not with case. sample O/P

./test-back.sh ws-23.host.com ws-23.host.com Unknown server 

Any Idea ?

like image 317
Unni Avatar asked Mar 09 '12 09:03

Unni


People also ask

Does bash use regular expressions?

Since version 3 (circa 2004), bash has a built-in regular expression comparison operator, represented by =~. A lot of scripting tricks that use grep or sed can now be handled by bash expressions and the bash expressions might just give you scripts that are easier to read and maintain.

How do you write a case statement in bash?

The case statement starts with the case keyword followed by the $variable and the in keyword. The statement ends with the case keyword backwards - esac . The script compares the input $variable against the patterns in each clause until it finds a match.

What is regular expression in shell script?

A regular expression (regex) is a text pattern that can be used for searching and replacing. Regular expressions are similar to Unix wild cards used in globbing, but much more powerful, and can be used to search, replace and validate text.


1 Answers

Bash case does not use regular expressions, but shell pattern matching only.

Therefore, instead of regex ws-[0-9]+\.host\.com you should use pattern ws*.host.com (or ws-+([0-9]).host.com, but that looks a bit advanced and I've never tried that :-)

like image 163
che Avatar answered Sep 21 '22 23:09

che