Single line while loop updating array

非 Y 不嫁゛ 提交于 2019-12-11 04:29:32

问题


I am trying to build a while loop that updates the values in an array but I keep getting a command not found error.

i=1
bool=true
declare -a LFT
declare -a RGT
while read -r line; do
  ${LFT[$i]}=${line:0:1}; ${RGT[$i]}=$(wc -l < temp$i.txt);
  if [ ${LFT[$i]} -ne ${RGT[$i]} ]; then
    $bool=false;
  fi;
  ((i=i+1));
done<output2.txt

The file I am reading from contains a single digit on each line, and I want to fill the array LFT with each entry being the digit. The array RGT should be filled with the line counts of files denoted temp*.txt. And I want to test to make sure each entry of these two arrays are the same.

However, I keep getting an error: command =# not found, where # is whatever digit is on the line in the file. Am I assigning values to the arrays incorrectly? Also, I get the error: command true=false not found. I am assuming this has something to do with assigning values to the boolean. Thanks


回答1:


The issue is on these lines:

${LFT[$i]}=${line:0:1}; ${RGT[$i]}=$(wc -l < temp$i.txt);

Change it to:

LFT[$i]=${line:0:1}; RGT[$i]=$(wc -l < temp$i.txt);

Valid assignment in shell should be:

var=<expression>

rather than

$var=<expression> ## this will be interpreted by the shell as a command

This is one of the common mistakes Bash programmers do. More Bash pitfalls here.



来源:https://stackoverflow.com/questions/42053783/single-line-while-loop-updating-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!