spbr
spbr

Reputation: 23

Bash Script - Invalid Arithmetic Operator

with the below code I keep getting the following errors:

#!/bin/bash
    sourceFile="file1.log"
    targetFile="/etc/network/interfaces"
    numLines=$(wc -l ${sourceFile})
    if (( counter >= "$numLines" || ! -f "${sourceFile}" )); then
            echo "invaild file"
            exit 0
    fi
    while [ "$counter" -le "$numLines" ]; do
            sed -i "${2} s/.*/wireless-key s: $(sed -n "${counter}"p <<< "${sourceFile}")/" "${targetFile}"
            counter=$((counter + 1))
    done

with the above code I keep getting the following errors:

  > ./2test.sh: line 5: ((: counter >= 12 file1.log || ! -f file1.log : syntax error: invalid arithmetic operator (error token is ".log || !
  > -f file1.log ") ./2test.sh: line 9: [: : integer expression expected

Upvotes: 1

Views: 869

Answers (1)

Biffen
Biffen

Reputation: 6355

Turning my comment into an answer.

wc with an explicit filename includes that filename in the output, so:

wc -l ${sourceFile}

Prints:

12 file1.log

That's then the value of $numLines.

The clue is in the error message: It includes the expanded expression:

> ./2test.sh: line 5: ((: counter >= 12 file1.log || ! -f file1.log : syntax error[…]
                                     ^^^^^^^^^^^^

You can avoid getting that filename by redirecting the file's contents to wc instead:

numLines="$(wc -l < "${sourceFile}")"

(The added quotes are thrown in as it's a good habit. (No, they're not strictly necessary in this case.) (And yes, the qoutes are correct, even if SO's syntax highlighter doesn't quite seem to understand them.)

There are other issues in the script (mentioned in the comments), but one question at a time. I will take the opportunity to recommend ShellCheck, though.

Upvotes: 3

Related Questions