foo="/sdf/here/jfds"
bar="${foo##*/}"
Canyone explain how the "${foo##*/}
" expression works because I understand it will return the string after the last forward slash (ie jfds) but I have no idea how it does it (or what this type of expression is called)?
It is one of several shell features, generically called shell expansion. This particular expansion is called parameter expansion*.
You can think of this particular shell expansion form as a left-truncate string function. You must use the curly braces as shown (that is not optional)..
When you use only one
#
, it means left-truncate only the first occurrence of the pattern which follows (up to the closing}
. When you use two##
, it means left-truncate all consecutive pattern-matches. The result ofvar="a/b/c"; echo ${var#*/}
isb/c
...echo ${var##*/}
returnsc
.There is a complementary right-truncate. It uses
%
instead of the#
... (I "remember" which is which because#
is like a bash comment; always on the left).The
*
is treated as a bash wildcard expansion.Here is a list of all shell expansions, presented in precedence order.
The order of expansions is: