语法错误:无效的算术运算符(错误标记为“.txt”)

时间:2017-03-16 21:53:28

标签: bash syntax-error

我在if语句行收到错误syntax error: invalid arithmetic operator (error token is ".txt")。我通过echo $words_in_line检查words_in_line并输出数字,所以我不明白为什么我会收到此错误。我该如何解决?

#!/usr/bin/env bash

#Outputs the lines that match wordcount range specified by min, $1, and max, $2
function get_correct_lines_in_file() {
     while read line ; do
        words_in_line=$( echo "$line" | wc -w );
        if [[ words_in_line -ge $1 ]] && [[ words_in_line -le $2 ]]; then #ERROR HERE
            echo "$line" >> MARBLES.txt
        fi
    done < $1
}

#Check if $1 and $2 arguements exists- are NOT NULL
if [[ "$1" != "" ]] && [[ "$2" != "" ]]; then
    for i in ${*:3} 
    do
        #If is a file you can read 
        if [[ -r $i && -f $i ]]; then
            echo "$i exists and is readable"
            get_correct_lines_in_file "$i"
        #If file doesn't exist
        elif [[ ! -f $i ]]; then
            echo $i >> FAILED.log
        fi
    done
fi

1 个答案:

答案 0 :(得分:1)

如果您希望在函数中访问最小值和最大值,则需要通过它们。考虑在函数中接受三个参数,并通过以下方式显式传递函数的参数:

get_correct_lines_in_file() {
     local -a words
     while read -r -a words ; do
        words_in_line=${#words[@]};
        if (( words_in_line >= $2 )) && (( words_in_line <= $3 )); then
            printf '%s\n' "${words[*]}"
        fi
    done <"$1" >>MARBLES.txt
}

...稍后,将文件名传递给函数$1,将脚本的$1作为函数$2,将脚本的$2作为函数$3

get_correct_lines_in_file "$i" "$1" "$2"