views:

134

answers:

3

I just saw some code in bash that I didn't quite understand. Being the newbie bash scripter, I'm not sure what's going on.

echo ${0##/*}
echo ${0}

I don't really see a difference in output in these two commands (prints the script name). Is that # just a comment? and what's with the /*. If it is a comment, how come it doesn't interfere with the closing } bracket?

Can anyone give me some insight into this syntax?

A: 

See the Parameter Expansion section of the bash(1) man page.

Ignacio Vazquez-Abrams
+2  A: 

Linux tip: Bash parameters and parameter expansions

${PARAMETER##WORD}  Results in removal of the longest matching pattern from the beginning rather than the shortest.
for example
[ian@pinguino ~]$ x="a1 b1 c2 d2"
[ian@pinguino ~]$ echo ${x#*1}
b1 c2 d2
[ian@pinguino ~]$ echo ${x##*1}
c2 d2
[ian@pinguino ~]$ echo ${x%1*}
a1 b
[ian@pinguino ~]$ echo ${x%%1*}
a
[ian@pinguino ~]$ echo ${x/1/3}
a3 b1 c2 d2
[ian@pinguino ~]$ echo ${x//1/3}
a3 b3 c2 d2
[ian@pinguino ~]$ echo ${x//?1/z3}
z3 z3 c2 d2
Paul Creasey
+1  A: 

See the section on Substring removal:

${string##substring}

Deletes longest match of $substring from front of $string.

The * is a wildcard. The command ${0##/*} prints the value of $0 unless it starts with a forward slash, in which case it prints nothing.

Mark Byers
`${string##substring}` removes a literal substring, not $substring
Paul Creasey