Home > other >  Bash - define a variable value with sed and extract with if condition
Bash - define a variable value with sed and extract with if condition

Time:12-08

I have been struggling to define a variable value with sed, compare the value to "6.7" and then write to a file.

The value is a version so it's always an int or a double. However my code doesn't seem to work:

FILE="user/gradle-6.7-new"
VERSION=$(sed -n '/^distributionUrl=/s/.*gradle-\([^-]*\)-.*/\1/p' $FILE)
if [[ $VERSION > 6.7 ]]
then
  $VERSION > /tmp/version_file
fi

Thanks.

CodePudding user response:

awk may be an easier approach.

#!/usr/bin/env bash
FILE="user/gradle-6.7-new"
awk -F- '{version=$2} version >= 6.7 { print version > "/tmp/version_file" }' <<< $FILE

CodePudding user response:

Assumptions:

  • OP's current code properly populates VERSION (ie, I'm assuming OP is not having problems populating VERSION from $FILE)

I'd recommend reviewing the answers @ this link.

While not chosen as the accepted answer, a variation on this answer is relatively straight forward, ie, let sort/-V order the two version strings to be compared and then test the first (or last) line of the sort/-V output accordingly, eg:

testVERSION='6.7'

for VERSION in 6.6 6.7 6.7.0 6.7.1 6.71
do
    op='<'
    if [[ $(printf "%s\n%s\n" "${testVERSION}" "${VERSION}" | sort -V | head -1) == "${testVERSION}" ]]
    then
        op='='    # at this point we know ${VERSION} >= ${testVERSION}, but assuming OP needs to distinguish between '>=' and '>' we need one more test ...

        [[ "${VERSION}" != "${testVERSION}" ]] && op='>'
    fi
    echo "${VERSION} ${op} ${testVERSION}"
done

This generates:

6.6 < 6.7
6.7 = 6.7
6.7.0 > 6.7
6.7.1 > 6.7
6.71 > 6.7

From here OP should be able to adapt the logic to generate the desired result, eg:

testVERSION='6.7'

[[ $(printf "%s\n%s\n" "${testVERSION}" "${VERSION}" | sort -V | head -1) == "${testVERSION}" ]] &&
[[ "${VERSION}" != "${testVERSION}" ]] &&
echo "$VERSION" > /tmp/version_file           # we get this far if ${VERSION} > ${testVERSION}
  • Related