Categories
bash scripting

Bash Conditionals with RegEx and other Comparisons

There are many times when using regular expressions for comparisons is the best option. In this case a bash script being written for a cron job required date format comparison. Using a regular expression makes it easy and easily adjustable if needed in the future to handle other formats.

The quick comparison of a variable to a date, yesterday, in this case.

#!/bin/bash

if [[ $today =~ \d{4}-\d{2}--\d{2} ]];then
    ...
fi

Note that there is no handling of the actual year, month, or day however, in most cases this would be necessary. There will be addition to this post down the line when time permits.

Sub-process Results

When waiting for the resutn of a co-process with a conditional such as this:

if $(tar caf archive.tar.bz2 ./files-to-archive);then
    do somehhing...
fi

In the previous example the conditional is based on the result of the co-process, the tar command in this situation. I have seen and experienced several ways and am wondering what is ideal in what situation. (i.e. should there be square brackets around the co-process command?) Does that make a difference? Does the spacing, if their included, make a difference. So necessary testing as in any project must be done.

This will not be automated just some quick trial and error.

Attempt #1

sans the square brackets.

if $(tar caf archive.tar.bz2 ./files-to-archive);then
    do somehhing...
fi

Leave a Reply