Concatenating bash variables and Parameter Expansion

by admin on

Sometimes you have to concatenate bash variables. For example, to form a particular filename, you might have a code like this:

As you might have noticed, we have a lot of underscores (in case you don’t know, it’s the symbol _),some part of the variable name,some other not.

If you run (WARNING: do not run this script on production or important files!!!)

you (or at least I) expected to find my moved and renamed file with a full path like this:
/done_files/newName_20150828.done

Well, what you’ll find is this:
/done_files/20150828.done

And if you have run this script multiple times,well,you lost all your files except the last one.

Why this?What can I do?

SHORT ANSWER

The problem is that underscore is a valid character in variable name. To avoid having bash interpreter searching for the wrong variable,you have to put variable name between curly brackets,like this

This way, bash will search for variable name and not for name_ .

LONG ANSWER

Bash interpreter will search for $name_ in variables, won’t find it,so it assumes that it has no value and adds an empty string to your filepath.
That’s, as I said before, because _ is a valid character in variable name! From bash manual, Parameters section:

[blockquote align=left]
A parameter is an entity that stores values. It can be a name, a number, or one of the special characters listed below under Special Parameters. A variable is a parameter denoted by a name.
[/blockquote]

And again, from bash manual, Definitions section:

[blockquote align=left]
name: A word consisting only of alphanumeric characters and underscores, and beginning with an alphabetic character or an underscore. Also referred to as an identifier.
[/blockquote]

So, a variable name can consist only of these characters: a-z A-Z 0-9 _

Underscore is one of them, so in our case it is interpreted by bash as part of the variable name, so it doesn’t find the variable, so it outputs an empty string.

Curly Braces ( that is {} )  in bash are called “Parameter Expansion”.  When you use it in a simple way, like ${name}, it simply reference the variable inside the braces. In this way, you can execute commands like the ones above, concatenating variables and string without problems. Another example of this feature (taken from ) is:

Anyway, curly braces and in general parameter expansion allow to do many more things!! I won’t talk about it here, but I’ll give you this page:

Bash Hackers Wiki – Parameter Expansion

where you can find almost all of parameter expansion functionalities – and related syntax.

Written by: admin

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *