kusayu
kusayu

Reputation: 93

How to use comparison in bash

I'm trying to use comparison in bash, but just can't make it work.

#!/bin/bash
str="75.00 W, 170.00 W"
function str_check {
    pow_array=()
    regexp='([0-9]+)\.[0-9]+[[:space:]]W,[[:space:]]([0-9]+)\.[0-9]+[[:space:]]W'
    [[ $str =~ $regexp ]] && for (( i = 0; i < 3; i++ )); do
        pow_array+=("${BASH_REMATCH[$i]}")
    done
    if [ "$1" -lt ${pow_arr[1]} ]; then
        echo "Available power limit is ${pow_array[0]}"
        echo "Setting up ${pow_array[1]}"
    elif [ "$1" -gt "${pow_arr[2]}" ]; then
        echo "Available power limit is ${pow_array[0]}"
        echo "Setting up ${pow_array[2]}"
    else
        echo "All good, setting up $1"
    fi
}

str_check "70"
str_check "100"
str_check "200"

Already have tried '[[', '((' '[', qoute and unquote everething, but getting all kind of errors or wrong results. Need someone to give me a hand.

./t.sh: line 9: [: 70: unary operator expected

./t.sh: line 12: [: : integer expression expected

Upvotes: 0

Views: 75

Answers (1)

Aaron
Aaron

Reputation: 24802

Time to discover shellcheck !

Line 9:
    if [ "$1" -lt ${pow_arr[1]} ]; then
                  ^-- SC2154: pow_arr is referenced but not assigned (did you mean 'pow_array'?).
                  ^-- SC2086: Double quote to prevent globbing and word splitting.

Change all the references to pow_arr into pow_array and it works !

Upvotes: 5

Related Questions