Search code examples
regextestingautoconf

What is the best way to specify a wildcard or regex in a "test" statement in configure.ac?


I am writing a configure.ac script for gnu autotools. In my code I have some if test statements where I want to set flags based on the compiler name. My original test looked like this:

if test "x$NETCDF_FC" = xifort; then

but sometimes the compiler name is more complicated (e.g., mpifort, mpiifort, path prepended, etc...), and so I want to check if the string ifort is contained anywhere within the variable $NETCDF_FC.

As far as I can understand, to set up a comparison using a wildcard or regex, I cannot use test but instead need to use the double brackets [[ ]]. But when configure.ac is parsed by autoconf to create configure, square brackets are treated like quotes and so one level of them is stripped from the output. The only solution I could get to work is to use triple brackets in my configure.ac, like this:

if [[[ $NETCDF_FC =~ ifort ]]]; then

Am I doing this correctly? Would this be considered best practices for configure.ac or is there another way?


Solution

  • Use a case statement. Either directly as shell code:

    case "$NETCDF_FC" in
        *ifort*)
            do_whatever
            ;;
        *)
            do_something_else
            ;;
    esac
    

    or as m4sh code:

    AS_CASE([$NETCDF_FC],
            [*ifort*], [do_whatever],
            [do_something_else])
    

    I would not want to rely on a shell capable of interpreting [[ ]] or [[[ ]]] being present at configure runtime (you need to escape those a bit with [] to have the double or triple brackets make it into configure).

    If you need a character class within a case pattern (such as e.g. *[a-z]ifort*), I would advise you to check the generated configure file for the case statement patterns which actually end up being used until you have enough [] quotes added around the pattern in the source configure.ac file.

    Note that the explicit case statements often contain # ( shell comments at the end of the lines directly before the ) patterns to avoid editors becoming confused about non-matching opening/closing parentheses.