0

I have this Bash script that has a basic if...else operator but the script doesn't seem to recognise the values correctly, and just continues the script, when it should stop and show an error.

I believe it's because I am using a float number, and bash can't tell. Here's the script:

Note: the error function is just a customer function

while getopts ":mh" opt; do
    case $opt in
        m)
            version="${OPTARG}"
            ;;
        \?)
            error "-$OPTARG is not a valid option. Use '-h' for more options" 'warn'
            ;;
        *|h)
            usage
            ;;
    esac
done
echo ${version} # here for debugging - this is either blank, or '0'
shift $((OPTIND-1))

[[ -z ${version} ]] && version=5.7

[[ "${version}" -lt "5.5" || "${version}" -gt "5.7" ]] &&
    error "Valid MySQL versions: 5.5 - 5.6 - 5.7" 'error'
echo ${version} # this then becomes '5.7' further down the script

So obviously I want the script to exit if the value of -m is less than 5.5 or greater than 5.7. Again I think it's to do with the value being a float.

Any help is appreciated.

Chris Mellor
  • 347
  • 5
  • 15

1 Answers1

0

You can use bash expansion to take a default version and regex to validate them. It is better to validate with regex instead -le and -ge because you can specify a list of valid options.

version=${version:-5.7}
[[ "$version" =~ ^(5\.5|5\.6|5\.7)$ ]] || error "Valid MySQL versions: 5.5 - 5.6 - 5.7"
Joao Morais
  • 1,885
  • 13
  • 20