tags:

views:

129

answers:

2

I have a tgz file which contains a version file, version.txt. This file has only one line "version=1.0.0". This tgz file is present in two different directories and has the same name.

My requirement is that I need to use bash script and awk to determine which of these two tgz files is of the latest version. i.e. tgz file having 1.0.0 is of a lower version than the file having version 1.0.1.

A: 

Use tar -xzvf /mnt/cf/bundle.tgz -O version.txt to extract the version.

The tricky part is how to handle the version. If your version has always three digits, then I suggest to multiply each part with 1000. That will give you a large number which you can easily compare. I.e. 1.0.0 == 1000000000; 1.0.1 = 1000000001. Another option is to format each part with %04d: 0001.0000.0000 and 0001.0000.0001. These strings can be compared.

Aaron Digulla
+1  A: 

Apologies for the downvote and the negative comment, but I'm always suspicious of homework type questions. To make amends, I've done it for you. You don't need awk, it can all be done in bash.

Just set F1 and F2 to the correct filenames. I'll leave it as an exercise for you to accept them as command line arguments :)

#!/usr/bin/env bash
F1=f1.tgz
F2=f2.tgz
VERSION_FILE=version.txt
version1=`tar -xzf $F1 -O $VERSION_FILE|sed -e 's/.*version=//'`
version2=`tar -xzf $F2 -O $VERSION_FILE|sed -e 's/.*version=//'`

if [ "$version1" == "$version2" ]; then
    echo "$F1 and $F2 contain the same version: $version1, $version2"
    exit 0;
fi

(   # start a subshell because we're changing IFS

    # Assume F1 is the latest file unless we find otherwise below
    latest_file=$F1
    latest_version=$version1

    # set the Internal Field Separator to a dot so we can
    # split the version strings into arrays
    IFS=.

    # make arrays of the version strings
    v1parts=( $version1 )
    v2parts=( $version2 )

    # loop over $v1parts, comparing to $v2parts
    # NOTE: this assumes the version strings have the same
    # number of components. If wont work for 1.1 and 1.1.1,
    # You'd have to have 1.1.0 and 1.1.1
    # You could always add extra '0' components to the shorter array, but
    # life's too short...
    for ((i = 0 ; i < ${#v1parts[@]} ; i++ )); do
     # NOTE: ${#v1parts[@]} is the length of the v1parts array
     if [ "${v1parts[i]}" -lt "${v2parts[i]}" ]; then
      latest_file=$F2
      latest_version=$version2
      break;
     fi
    done
    echo "$latest_file is newer, version $latest_version"
)
edoloughlin