Single line while loop updating array

2019-07-29 11:30发布

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条回答
我命由我不由天
2楼-- · 2019-07-29 11:56

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.

查看更多
登录 后发表回答