0

I wanted to directly comment on another post asking the person directly, but I cannot comment, and it doesn't seem like I can message him either therefore I will ask the good community for assistance.

On the post in question (found here) I have been reading the man page... but I do not understand how the following code works.

srv=`expr "$SERVER" : '^\(db\|bk\|ws\)-[0-9]\+\.host\.com$'`
echo -n "$SERVER : "
case $srv in
  ws) echo "Web Server" ;;
  db) echo "DB server" ;;
  bk) echo "Backup server" ;;
  *) echo "Unknown server !!!"
esac

Taking this line by line, I understand that the input to the script ($#)would be compared by the expr command to the latter stated regex... and that the output of that would be 0, 1, 2, or 3. The output would then be stored into the $svr variable...

Unless I am misunderstanding the code... wouldn't that mean that the answer would always be:

"Unknown server !!!"

I appreciate the help in advance!! Thank you!

Community
  • 1
  • 1
rustysys-dev
  • 843
  • 1
  • 11
  • 22
  • The easiest way to prove or disprove this kind of doubt _is to try the code_. `SERVER=db-1.host.com` and then paste the code in the question into the terminal - the answer is not "Unknown server !!!" – AD7six Jul 26 '15 at 16:04

2 Answers2

1

The first command extracts the first two characters of a string from the variable $SERVER, if it matches the pattern (that's what the parentheses around the \(db\|bk\|ws\) part do). So the variable $srv will contain one of the three db, bk or ws if the string matches, otherwise it will contain 0.

It's worth mentioning that it isn't necessary to use expr anymore, as this can be achieved using bash regular expressions:

re='^(db|bk|ws)-[0-9]+\.host\.com$'
[[ $SERVER =~ $re ]] && srv=${BASH_REMATCH[1]}

As bash supports extended regular expression syntax, it is not necessary to escape the parentheses around the capture group or the |.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
1

command to the latter stated regex... and that the output of that would be 0, 1, 2, or 3.

No. This part \(db\|bk\|ws\) means that if it matches this part and the surrounding part, because of the parentheses capture group, the result of expr will be that inside of the capture group that matched, so either db, bk or ws.

tomsv
  • 7,207
  • 6
  • 55
  • 88