http://www.politiker-stopp.de/gfx/politiker-stopp-print.png

Benjamin Schieder

[SOLUTIONS] FIXING YOUR VARIABLES

2006 February 14 | 2 comments

In bash, you can call variables in two ways:

${variable}
$variable

The first is better for a number of reasons:
First: Variable operations
There are several operations you can do on a variable, each one requiring the curly brackets:
Remove string at the end of the variable:
var="123ABC"
var=${var%ABC}
echo ${var}
123

Remove string at the beginning of the variable:
var="123ABC"
var=${var#123}
echo ${var}
ABC

Replace part of the variable:
var="123ABC"
var=${var/3A/A3}
echo ${var}
12A3BC


So it is at least a good habit to have a clean look in your script.

Second: String operations
Assume the following scenario: You have a variable 'var' that contains a string that you want to suffix with another string. Example:
var="ABC"
echo "$varDEF"

This will not work because 'varDEF' is also a variable.
echo "${var}DEF"

This will work because you explicitly reference the variable 'var'.

Now, if you already have a bunch of scripts that use the '$var' style and want to transform them into '${var}' style, doing it manually is a tedious job.
For vim users, I have this solution:
:%s/$([A-Za-z0-9_@$]+)/${1}/g

This regular expression will wrap all variables in curly brackets.

EOF

Category: blog

Tags: Solutions


2 Comments

From: Anonymous

I think your editor ate the backslashes of the Vim command. Replacing parts of a variable really seems to work with Bash only. While it's less efficient, you can do all so with sed as well which should be the method of choice for scripts except in-house solutions maybe.

From: Roino
2009-10-05 13:52:13 +0200

i wanna know the use of variable editor...if anyone knows plz tell me through ma email

Post a comment

All comments are held for moderation; basic HTML formatting is accepted.

Name: (required)
E-mail: (required, not published)
Website: (optional)
Comment: