BASH v4 Regular Expressions

Posted: 2011-03-05 14:09:48 by Alasdair Keyes

Direct Link | RSS feed


I've recently built a new backup server using NILFS for it's handy snapshotting capability. I'll get onto that in another post, but because NILFS support was only added into the Linux 2.6.30 kernel, our current CentOS 5 build's don't have support for it as they only run 2.6.18.

To overcome this, I built the new box up with Ubuntu 10.10 Server. However, it appears that I'd never written any BASH scripts using regular expressions in Ubuntu. I copied my custom backup scripts from our old box to the new backup server and ran them and it errored on some path name checks I performed. Upon investigation it appears that BASH v4's regular expression handling isn't backwards compatible with version 3. Specifically the use of the $ character as the End of Line character

As a test...

#!/bin/bash
TESTDIR="/tmp/a/";

if [[ $TESTDIR =~ '/$' ]]; then
        echo "$TESTDIR has a trailing slash";
else
        echo "$TESTDIR has no trailing slash";
fi

The output is

/tmp/a/ has no trailing slash

Which doesn't seem too clever to me. After some looking through the bash documentation I found out about the 'shopt' builtin which allows you to change additional shell behavior.

Long story short, so I don't have to go round changing all the regex in my code, if I add something like this to the top of all my scripts, they can port between Bash v3 and v4 seamlessly...

#!/bin/bash

BASH_VER=`/bin/bash --version | grep 'version 4'`;
if [ -n "$BASH_VER" ]; then
        echo "Detected BASH v4 - Switching on Version 3 compatibility"
        shopt -s compat31
else
        echo "Not Detected BASH v4"
fi

TESTDIR="/tmp/a/";

if [[ $TESTDIR =~ '/$' ]]; then
        echo "$TESTDIR has a trailing slash";
else
        echo "$TESTDIR has no trailing slash";
fi

Produces more expected output

Detected BASH v4 - Switching on Version 3 compatibility
/tmp/a/ has a trailing slash

Or if you're not bothered about nice output, shorten the check to..

if [ -n "`/bin/bash --version | grep 'version 4'`" ]; then
        shopt -s compat31
fi


If you found this useful, please feel free to donate via bitcoin to 1NT2ErDzLDBPB8CDLk6j1qUdT6FmxkMmNz

IT Consultancy Services

I'm now available for IT consultancy and software development services - Cloudee LTD.



Happy user of Digital Ocean (Affiliate link)


Version:master-619e08f203


Validate HTML 5