3

Can someone explain what this does in a linux shell.....

port=$((${devpath##*[-.]} - 1))

I have a variable named $devpath, and one possible value is /sys/bus/usb/devices/usb2/2-1.

I'm assuming that ${devpath##*[-.]} performs some sort of regex on $devpath, but it makes no sense to me. Nor does *[-.] which I understand to mean "one of more of any one of the character '-' or any other character except newline"

When running through a script (this is from usb-devices.sh), it seems that the value of port is always the first numeric digit. Something else that confuses me is the '-1' at the end, shouldn't that reduce whatever ${devpath##*[-.]} does by one?

I tried looking up regex in shell expressions but nothing made any sense and no where could I find an explanation for ##.

1
  • How are we supposed to know without looking at your whole script?? Commented May 5, 2015 at 13:43

2 Answers 2

5

Given the variable:

r="/sys/bus/usb/devices/usb2/2-123.45"

echo ${r##*-} returns 123.45 and echo ${r##*[-.]} returns 45. Do you see the pattern here?

Let's go a bit further: the expression ${string##substring} strips the longest match of $substring from the front of $string.

So with ${r##*[-.]} we are stripping everything in $r until the last - or . is found.

Then, $(( )) is used for arithmetic expressions. Thus, with $(( $var - 1 )) you are subtracting 1 from the value coming from ${r##*[-.]}.

All together, port=$((${devpath##*[-.]} - 1)) means: store in $port the value of the last number after either - or . at the end of $devpath.

Following the example below, echo $((${r##*[-.]} - 1)) returns 44 (45 - 1).

Sign up to request clarification or add additional context in comments.

2 Comments

To complete, all these syntaxes are described here: tldp.org/LDP/abs/html/string-manipulation.html (in the Substring Removal part)
@CasimiretHippolyte sure, only that I would recommend going through the original source: Bash reference manual #Shell Parameter Expansion.
5

There is no regex here. ${var##pattern} returns the value of var with any match on pattern removed from the prefix (but this is a glob pattern, not a regex); $((value - 1)) subtracts one from value. So the expression takes the number after the last dash or dot and reduces it by one.

See Shell Parameter Expansion and Arithmetic Expansion in the Bash manual.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.