The Cookie Machine - Click here to drag window

DUMMY TEXT - Real text set in assets/js/theCookieMachine.js

If you can read me, I'm broken!

Views: 21,681ā€…    Votes:  2ā€…
Tags: command-line   bash   scripts   versions  
Link: šŸ” See Original Answer on Ask Ubuntu ā§‰ šŸ”—

Title: Check if Bash version is >= given version number
ID: /2017/05/21/Check-if-Bash-version-is-__-given-version-number
Created: May 21, 2017    Edited:  August 5, 2019
Upload: December 3, 2023    Layout:  post
TOC: false    Navigation:  false    Copy to clipboard:  false

One-liner not possible but a bash script is possible

I developed a script that draws on answers in Stack Overflow. One of those answers led to a Dell Employee writing version number comparisons in 2004 for the DKMS application.

The code

The bash script below needs to be marked as executable using the command chmod a+x script-name. Iā€™m using the name /usr/local/bin/testver:


# NAME: testver
# PATH: /usr/local/bin
# DESC: Test a program's version number >= to passed version number
# DATE: May 21, 2017. Modified August 5, 2019.

# CALL: testver Program Version

# PARM: 1. Program - validated to be a command
#       2. Version - validated to be numberic

# NOTE: Extracting version number perl one-liner found here:

#       Comparing two version numbers code found here:

# Map parameters to coder-friendly names.

# Program name must be a valid command.
command -v $Program >/dev/null 2>&1 || { echo "Command: $Program not found. Check spelling."; exit 99; }

# Passed version number must be valid format.
if ! [[ $Version =~ ^([0-9]+\.?)+$ ]]; then
    echo "Version number: $Version has invalid format. Aborting.";
    exit 99

InstalledVersion=$( "$Program" --version | perl -pe '($_)=/([0-9]+([.][0-9]+)+)/' )
# echo "Installed Version: $InstalledVersion"

if [[ $InstalledVersion =~ ^([0-9]+\.?)+$ ]]; then
    l=(${InstalledVersion//./ })
    r=(${Version//./ })
    [[ ${#r[@]} -gt ${#l[@]} ]] && s=${#r[@]}

    for i in $(seq 0 $((s - 1))); do
        # echo "Installed ${l[$i]} -gt Test ${r[$i]}?"
        [[ ${l[$i]} -gt ${r[$i]} ]] && exit 0 # Installed version > test version.
        [[ ${l[$i]} -lt ${r[$i]} ]] && exit 1 # Installed version < test version.

    exit 0 # Installed version = test version.
    echo "Invalid version number found for command: $Program"
    exit 99

echo "testver - Unreachable code has been reached!"
exit 255
ā‡§ Why my Ubuntu 16.04 can't connect to wired when I change kernel to 4.2 How is the "WannaCry" Malware spreading and how should users defend themselves from it?  ā‡©