0

Using the test built-in to compare my variable to an array fails with error "Syntax error in expression".

I've tried requoting the var_names, using == and -eq, and several old tricks from SO questions from 8+ years ago.

#!/bin/bash

TOTAL=0
declare -a FREQ=(0);

main(){
    for i in $(cat "$1");
    do
        TOTAL=$(( $i + FREQ[-1] ))
        echo Total is $TOTAL

        if [[ $TOTAL -eq "${FREQ[@]}" ]];
        then
            echo "Matching Frequency Found: " $TOTAL
            exit
        else
            FREQ=(${FREQ[@]} $TOTAL)
        fi

    done

    return $TOTAL
    return $FREQ
}

main $@

I expect $TOTAL to be found in the array of $FREQ when the script is called with ./script.sh input.txt which holds over 1000 integers.

Barmar
  • 596,455
  • 48
  • 393
  • 495
  • You can't return two values from a function. – Barmar Dec 21 '18 at 18:44
  • 1
    To add a new element to an array use `FREQ+=($TOTAL)` – Barmar Dec 21 '18 at 18:46
  • Duplicate of [check if a bash array contains a value](https://stackoverflow.com/questions/3685970/check-if-a-bash-array-contains-a-value) – Barmar Dec 21 '18 at 18:49
  • Technically, you can't return *any* value from a variable, unless you are abusing the exit status. The exit status can only be an integer between 0 and 255. – chepner Dec 21 '18 at 19:44

1 Answers1

0

I'm not sure I get what you're trying to do, but try a lookup table.

TOTAL=0
declare -a FREQ=(0)
declare -A lookup=( [0]=1 )
while read -r i
do  TOTAL=$(( $i + FREQ[-1] ))
    if (( ${lookup[$TOTAL]} ))
    then  echo "Matching Frequency Found: " $TOTAL
          exit
    else  lookup[$TOTAL]=1
          FREQ+=($TOTAL)
    fi
done < "$1"

As that logic stands, though, I don't think it will ever hit a found frequency unless some of them are negative...

Paul Hodges
  • 8,723
  • 1
  • 12
  • 28