Last night at my C/Unix class the professor quickly glossed over an interesting shell scripting technique that allows you to strip stuff off the beginning or end of a variable. I forgot about it until I saw the technique used again while editing a shell script at work today.
I didn't know what the technique was called but I remembered the professor saying something about "greedy clobbering" and, since I cannot search Google for special characters, I Googled "Bash greedy" and luckily found 10 Steps to Beautiful Shell Scripts, which just so happened to contain the technique I was looking for (#5).
There are basically four versions of this technique:
varfrom left-to-right and return everything after the first occurrence of
varfrom left-to-right and return everything after the last occurrence of
varfrom right-to-left and return everything after the first occurrence of
varfrom right-to-left and return everything after the last occurrence of
Here's how it works. Let's say you have a variable that contains the path to a file:
Now let's say you wanted to extract the
myscript.sh part from that variable. You could do some funky stuff with awk but there is a much easier solution built into Bash:
$SCRIPTNAME will contain
##*/ tells the shell to search left-to-right for everything before and including the slash (
*/), be greedy while doing it so that all the slashes will be found (
##), and then return whatever is left over (in this case,
myscript.sh is the only thing remaining after the last slash).
AFAIK, this is a Bash-specific feature, but I'm not entirely certain and I wasn't sure where I could look to find out. It's amazing how four characters can do so much work so easily. The more I learn about what I can do with Bash, the more I wonder how I ever lived without all this knowledge!