0

I've come across this curious bash expression:

somestring=4.5.6
echo ${somestring%rc*}

For all that I can tell it just prints 4.5.6. So why would anybody use it?

I found it in this script (look for pkgver), so I hope I didn't miss any context which is necessary for this to work.

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Faerbit
  • 33
  • 4
  • Read the [Bash manual page](http://man7.org/linux/man-pages/man1/bash.1.html), it's long but will tell you all you need to know. In your case, the [expansion chapter](http://man7.org/linux/man-pages/man1/bash.1.html#EXPANSION) contains the answer to your question. – Some programmer dude Jul 06 '15 at 09:43

3 Answers3

2

Source:

${string%substring} deletes shortest match of $substring from back of $string.

The intention is to echo the numerical version only, without the rc* suffix for strings like:

somestring=4.5.6rc1
somestring=4.5.6rc23_whatever

UPDATE:
The better choice is to echo ${somestring%%rc*}.
Otherwise, the following might happen:

somestring=4.5.6rc1_rc2
echo ${somestring%rc*}
4.5.6rc1_

whereas:

echo ${somestring%%rc*}
4.5.6
Eugeniu Rosca
  • 5,177
  • 16
  • 45
0

It removes rc and any following characters (the *) from somestring. See, e.g., this answer.

Community
  • 1
  • 1
cxw
  • 16,685
  • 2
  • 45
  • 81
0

This is known as parameter expansion.

From Bash manual:

${parameter%word}

${parameter%%word}

The word is expanded to produce a pattern just as in filename expansion. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the ‘%’ case) or the longest matching pattern (the ‘%%’ case) deleted. If parameter is ‘@’ or ‘’, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘’, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.


Simply "${somestring%rc*}" is the string left by cutting rc* (* means anything after rc) from $somestring from right i.e rc* is matched in the string from right and then deleted and the resultant is the remaining string.
Jahid
  • 21,542
  • 10
  • 90
  • 108