RegEx Confusion in a Linux shell script

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

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

      

I have a variable named $devpath

and one possible value is /sys/bus/usb/devices/usb2/2-1

.

I am assuming that $ {devpath ## * [-.]} Is executing some kind of regex on $ devpath, but it doesn't make sense to me. I also don't understand * [-.], Which I understand means "one of more than one character" - or any character other than newline "

When run through a script (this is from usb-devices.sh ), it seems that the port value is always the first numeric digit. Something else that confuses me is the "-1" at the end, shouldn't that do something ${devpath##*[-.]}

on one?

I tried to find regex in shell expressions but nothing made sense and there is no where I could find an explanation for ##

.

+3


source to share


2 answers


There is no regex here. ${var##pattern}

returns a value var

with any match on pattern

, removed from the prefix (but this is a glob pattern, not a regular expression); $((value - 1))

subtracts one from value

. Thus, the expression takes the number after the last stroke or point and decreases it by one.



Cm. A shell extension parameters and arithmetic expansion in Bash.

+5


source


Given a 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 go a little: the expression ${string##substring}

splits the longest match $substring

from the front $string

.



So, with the help ${r##*[-.]}

we shoot everything in $r

until the last -

or is found .

.

It is then used for arithmetic expressions $(( ))

. Thus, when $(( $var - 1 ))

you subtract 1

from the value coming from ${r##*[-.]}

.

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

means: store in the $port

value of the last number after -

or .

at the end $devpath

.

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

returns 44

(45 - 1).

+5


source







All Articles