Using sort as a Version Test in Bash

I have several bash scripts where I use readarray (aka mapfile) only if it will function on that system. This is dependent upon the version of bash being used. I have this test which is interesting enough to be worthy of some small discussion.

Here is the function that gets the bash version, makes the test, and then either uses mapfile (if the version is high enough) or uses read (if it is not). Basically, you are asking if the local version of bash is greater than or equal to x.x.x (your target version).

function func_getTorrentList() {
    local loc_bashVersion
    loc_bashVersion="$( bash --version | head -n1 | cut -d " " -f4 | cut -d "(" -f1 )"
    # readarray or mapfile -d fails before bash 4.4.0
    if printf '%s\n' "4.4.0" "${loc_bashVersion}" | sort -V -C ; then
        mapfile -d $'\0' A_torrentList < <( transmission-remote --list | sed -e '1d;$d;s/^ *//' | cut --only-delimited --delimiter=' ' --fields=1 )
        while IFS= read -r ; do
            A_torrentList+=( "$REPLY" )
done < <( transmission-remote --list | sed -e '1d;$d;s/^ *//' | cut --only-delimited --delimiter=' ' --fields=1 )

# bonus: surround the local version for limiting the test to a version range
    if printf '%s\n' "4.4.0" "${loc_bashVersion}" "6.6.6" | sort -V -C ; then
# or with variables
    if printf '%s\n' "${version_lowerLimit}" "${loc_bashVersion}" "${version_upperLimit}" | sort -V -C ; then


If you look at the if printf line you will see the last operation of the if is a sort call. In that sort call the -V tells sort to use version sorting. The -C tells sort to give true or false on whether any sorting was done.

If the first number (your target version) is the same or smaller than the second number (the local version of bash), then sort passes (-C is true). Otherwise, sort fails (and -C is false and so goes the if statement).

You can further create a range by surrounding the local version with lower- and upper-limit version numbers, as you see in the bonus line at the end.



Leave a Reply

Your email address will not be published. Required fields are marked *