Monday, December 15, 2008

Condition testing and braces

Hello and welcome to this weeks edition of Practical Shell Scripting. Recently I was handed a project to work on that was a rewrite of some perl code into shell script and I came across some new tricks that I was unaware of and I wanted to share some of them with you. In particular testing for conditions using metacharacters. I'm sure that all of you are aware of the simple test condition statements using brackets such as:

if [ -f foobar ]; then

which will test for the existence of a the file foobar, but something that you might not be aware of, and something that I was was previously unaware of is that bash can also do much more complex metacharacter testing through the use of double brackets. ie: [[

Here's an example of a simple test using the common metachacter ^.

##----------------------------------------------------------------##
#!/bin/bash

STRING_TO_READ="foobar"

if [ $STRING_TO_READ =~ ^foo ]; then
echo "We have foo"
else
echo "no foo here"
fi

## Note the double braces in the test condition statement ##
if [[ $STRING_TO_READ =~ ^foo ]]; then
echo "We have foo"
else
echo "no foo here"
fi

##--------------------------------------------------------------------------------------------##

For those unfamiliar with metacharacters the ^ symbol is used to specify the something at the start of a line. So here's the tricky part.... by taking a regular set of test brackets an adding a second pair of brackets around them you now have the capability of doing any of the functions that you could do in say sed of other unix tools. I'm just starting to play with this, but I'm sure that this tool will prove incredibly versatile in the future.

That's it for this week, be sure and drop me a line if you have any questions or comments. Happy coding

No comments: