[英]How do you search an array for a variable using bash's test [ ] built-in?
Using the test built-in to compare my variable to an array fails with error "Syntax error in expression"
. 使用内置测试将我的变量与数组进行比较失败,并显示错误"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. 我尝试使用==和-eq重新引用var_names,以及8年前SO问题中的一些老技巧。
#!/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. 我希望使用./script.sh input.txt
调用脚本时,可以在$ FREQ数组中找到$ TOTAL,该脚本可容纳1000个以上的整数。
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... 但是,按照这种逻辑,除非它们中的某些是负数,否则我认为它不会达到已知的频率。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.