variable#pattern

We can use the following construct to match things from the beginning of the variable field.

${variable#pattern}
            

Using our variable MAGIC again, the hash sign ( # ) will match the shortest pattern from the beginning of the variable. Let's try:

echo ${MAGIC#a*b}
            

Since the shortest pattern starting from the beginning of the string, beginning with an 'a', followed by zero or more characters and ending with a 'b' is 'ab', the output will be:

racadabra 
            

Conversely if we did:

echo ${MAGIC##a*b}
            

this will remove the longest match from the beginning of the string for an 'a' followed by zero or more characters followed by a 'b', leaving you with:

ra
            

How do we remember these things? Well, the way I remember them is as follows:

The hash is generally used to signify a comment line within a script. A comment should always start at the beginning of the line. So hashes" match from the beginning of the line.

How do we match an end of a line?

Well usually that's a dollar (say in "vi"), and a dollar looks fairly similar to a percentage sign if we've got a warped sense of vision. So % matches the end of the line.

How do you remember shortest and longest?

Well, % means shortest, %% means longest, # means shortest, ## means longest.

How do you write a pattern?

Turn back a good couple of chapters to refresh your memory on writing patterns.