简体   繁体   中英

How to use a variable in a grep regex string in a bash script

I have a script that I am using to download EJBCA Community. They do something a little different where they put a minor version inside of a major version. For example EJBCA Community 6.10.0 has a minor version inside that folder of 6.10.1.2.

    #Set build (This is actually passed as a command line argument in the main script.  But for clarity I am putting it here like this.    
    EJBCA_BUILD=6.10.0
    #Check to see if standard version URL works (no minor patched version)    
    STATUS="$(curl -s --head -w %{http_code} "https://sourceforge.net/projects/ejbca/files/ejbca6/ejbca_$EJBCA_BUILD/ejbca_ce_$EJBCA_BUILD.zip" -o /dev/null)"
            echo $STATUS
            #If it doesn't exist grep to find out what the patched version is and create $EJBCA_File with the version.
            if [ $STATUS = 404 ]; then
                    EJBCA_FILE="$(curl -s -L  "https://sourceforge.net/projects/ejbca/files/ejbca6/ejbca_$EJBCA_BUILD/ejbca_ce_$EJBCA_BUILD/" | grep -o -i "ejbca_ce_$EJBCA_BUILD_[0-9].zip" | head -n1)"
                    #Bring the URL together so we can download it.
                    EJBCA_URL=https://sourceforge.net/projects/ejbca/files/ejbca6/ejbca_$EJBCA_BUILD/$EJBCA_FILE.zip
            elif [ $STATUS = 200 ]; then
                    # If it works then download it as is.
                    EJBCA_URL=https://sourceforge.net/projects/ejbca/files/ejbca6/ejbca_$EJBCA_BUILD/ejbca_ce_$EJBCA_BUILD.zip
            else
                    echo -n "There was some other error returned from the server than 404 or 200.  Exiting."
                    echo -n "The error code was $STATUS"
            exit 1
            fi

The problem I am having is specifically the grep -o -i "ejbca_ce_$EJBCA_BUILD_[0-9].zip" part. I cannot get the variable inside the regex to work. I assume this is because its parsing it incorrectly and the variable comes up empty. Any help would be greatly appreciated.

Use curly braces to ensure your variable name is what you intended, eg, ${EJBCA_BUILD} - in this case, I suspect that because underscore ( _ ) is a valid variable character, you are unintentionally using the variable $EJBCA_BUILD_ which is unset, so is replaced by an empty string, resulting in your grep expression being grep -o -i "ejbca_ce_[0-9].zip" which isn't what you want.

You can see this by doing a simple test in your shell:

$ EJBCA_BUILD=dummy

$ echo "ejbca_ce_$EJBCA_BUILD_[0-9].zip"
ejbca_ce_[0-9].zip

$ echo "ejbca_ce_${EJBCA_BUILD}_[0-9].zip"
ejbca_ce_dummy_[0-9].zip

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM