rustysys-dev
rustysys-dev

Reputation: 863

Bash expr command logic

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!

Upvotes: 0

Views: 155

Answers (2)

Tom Fenech
Tom Fenech

Reputation: 74685

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 |.

Upvotes: 1

tomsv
tomsv

Reputation: 7277

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.

Upvotes: 1

Related Questions