Bash parameter expansion cheatsheet

Download Bash Cheatsheet

The bash shell has a powerful parameter expansion syntax, but it’s complex and hard to remember. I always forget which syntax does what, even though I use it all the time for scripts and one-off jobs. Unfortunately, I find the man page unhelpful as a reference, so I’ve made a cheat sheet for myself. Perhaps you’ll find it useful too.

If you want the whole story, type man bash into a terminal, and search for the section titled EXPANSION. There you’ll find the full details, such as this:

${parameter%word}
${parameter%%word}

The word is expanded to produce a pattern just as in pathname expansion. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the “%” case) or the longest matching pattern (the “%%” case) deleted. If parameter is @ or *, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.

Hence the need for the cheatsheet :-)

Technorati Tags:No Tags

You might also like:

  1. How to avoid VBScript regular expression gotchas

2 Responses to “Bash parameter expansion cheatsheet”


  1. 1 Francois Saint-Jacques

    O’Reilly’s ‘Classic Shell Scripting’ (ISBN 0-596-00595-4) is a must if you want dozen of small tips like theses.

    This one is really neat too: http://thesmithfam.org/blog/2006/05/23/bash-socket-programming-with-devtcp-2/

  2. 2 Xaprb

    Thanks for the tip! I’m currently on an Ubuntu machine and /dev/tcp isn’t enabled so I can’t test it out, but that is neat!

Leave a Reply

Please do not use this blog to get help with problems or bugs in Maatkit or innotop: use the Sourceforge forums, mailing list, or bug trackers. If you're asking for help with MySQL, please use the MySQL mailing list instead.