• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 349
  • Last Modified:

How echo ${instance##*/} expand by shell?

Hello, I am trying to understand following in bash scripts

[user@hostname]$ ls -ld /opt/product/jms/instances/etc/ac4-*
drwxr-xr-x  2 user company 4096 Oct 15 17:18 /opt/product/jms/instances/etc/ac4-sfae-dev
drwxr-xr-x  2 user company 4096 Oct 10 21:08 /opt/product/jms/instances/etc/ac4-sfae-prod
drwxr-xr-x  2 user company 4096 Oct 15 17:09 /opt/product/jms/instances/etc/ac4-sfae-stage
[user@hostname]$ for instance in /opt/product/jms/instances/etc/ac4-*; do echo ${instance##*/}; done
ac4-sfae-dev
ac4-sfae-prod
ac4-sfae-stage

Open in new window


here I would like to understand how ${instance##*/} is being expanded. I was thinking to use 'basename' but ${instance##*/} also serve my purpose. Though this is the first time I saw this variable so interested to know how does it work. Thanks!
0
beer9
Asked:
beer9
2 Solutions
 
raysonleeCommented:
${parameter##word}
The word (*/ in this case) is expanded to produce a pattern. If the pattern matches the beginning of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the longest matching pattern (the ‘##’ case) deleted.
(Therefore the whole path including the last / was deleted and leaving only the file names.)

Refer to http://www.gnu.org/s/bash/manual/bash.html for more details about bash commands.
0
 
farzanjCommented:
# means cut from the left side (first instance)
% means cut from the right side (first instance)
## cut from left side but the last instance
%% cut from left side but the last instance


Now say
> a='/opt/product/jms/instances/etc/ac4-sfae-dev'
> echo ${a#*/}              ---- Chops off the first instance of / and the rest is printed.
opt/product/jms/instances/etc/ac4-sfae-dev

> echo ${a##*/}    --matches any characters * and then should also match slash, all the match is chopped off from the left side
ac4-sfae-dev


Now lets chop off the first instance of / from the right side.
> echo ${a%/*}
/opt/product/jms/instances/etc

And the last instance of / from the right side
> echo ${a%%/*}
       NO OUTPUT --everything deleted.

Now suppose we had
b='opt/product/jms/instances/etc/ac4-sfae-dev'
> echo ${b%%/*}
opt



0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now