Sep 032012

This is a continuation of Bash Scripting Tricks and Techniques.


Script  Trick 2 – Variable Value Advanced Assignment

Assigning a variable a basic value is easy enough.




But assigning a variable the end value of a series of commands can come in handy.


[admin@wks01 ~]$ AppHome=$( grep HomeDir $( find . -name app.conf ) |grep -v '#' |cut -d " " -f 2 ) [admin@wks01 ~]$ echo $AppHome /opt/appdir

The above assigns the AppHome variable a value that is the result of several commands piped together. Also, notice the “$” before the parenthesis. It grep’s on the string HomeDir which possibly resides in a file called app.conf, but since we’re not sure where it resides, the find command is employed. When it is found, it makes sure there is no “#” on the same line and then extracts a field from the line. In this case, it was looking for the home directory for an application, and it found /opt/appdir.

There is no error checking in the above example, so if one of the piped commands doesn’t find what it’s looking for, things could get ugly.  Therefore, if deployed in a production environment of any significance, having some checks in place is recommended.  However, the above example is just an illustration of what can be done with variable assignments.