regexbashawkwindows-subsystem-for-linuxversion-numbering

Bash script is not maching regex


I truly don't understand what I'm missing here. I have a very basic script that need to check if text contains only number (more specific a semantic version for an app), then do some stuff.

The text.txt is something like this:

appVersion: 2.0.1

and this is my script

#!/bin/bash
appVersion=`cat test.txt | awk '/^appVersion:/{print $2}'`
echo "appVersion is " $appVersion
Version=3.1.5

if [[ $appVersion =~ [0-9]+(\.[0-9]+){2,3}$ ]] ; then
    echo "is a number" $appVersion 
 else
    echo "not a number" $appVersion 
fi`

Basically I cat from the text what I need, and then trying to pass that info in an if condition.

The problem is the script is basically not taking the variable appVersion every time I run it, it keep saying that there isn't any number in my variable, like is not matching the regex, but if I pass the variable $Version the script works.

By the way the echo "appVersion is " $appVersion is working (it's printing what I run inside appVersion), so the command inside my variable $appVersion is actually retrieving what I need.

I think I'm missing something with awk but I cannot understand what.

Edit:

I'm running this script on my local pc, on wsl2 ubuntu 20, as a test, to let then run it on linux azure devops agent


Solution

  • I suggest to replace

    appVersion=`cat test.txt | awk '/^appVersion:/{print $2}'`
    

    with

    appVersion=$(awk '/^appVersion:/{print $2}' test.txt | dos2unix)
    

    or with GNU awk

    appVersion=$(awk 'BEGIN{RS="\r\n"} /^appVersion:/{print $2}' test.txt)
    

    to convert Windows' carriage-returns.

    See: 8 Powerful Awk Built-in Variables – FS, OFS, RS, ORS, NR, NF, FILENAME, FNR