Home > Articles > Operating Systems, Server > Linux/UNIX/Open Source

Variable Mangling in bash with String Operators

  • Print
  • + Share This
"Mangling" may sound like something you don't want to happen to your code, but in this article Pat Eyler shows two very useful versions of variable substitution in bash--pattern matching and substitution.
Pat Eyler is the author of Networking Linux: A Practical Guide to TCP/IP (New Riders, 2001, ISBN 0-7357-1031-7).
From the author of

Abstract

Have you ever wanted to change the names of many files at once? How about using a default value for a variable if it has no value? These and many other options are available to you through string operators in bash and other Bourne shell derived shells.

String operators allow you to manipulate the contents of a variable without having to write your own shell functions to do so. They're provided through "curly brace" syntax. Any variable can be displayed like ${foo} without changing its meaning. This functionality is often used to protect a variable name from surrounding characters:

bash-2.02$ export foo=foo
bash-2.02$ echo ${foo}bar # foo exists so this works
foobar
bash-2.02$ echo $foobar # foobar doesn't exist, so this fails

   bash-2.02$

By the end of this article, you'll be able to use it for a whole lot more.

There are three kinds of variable substitution:

  • Pattern matching

  • Substitution

  • Command substitution

I'll talk about the first two and leave command substitution for another article.

  • + Share This
  • 🔖 Save To Your Account