Sean Morgan Sean Morgan - 4 years ago 71
Bash Question

Single line while loop updating array

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

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

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.

Answer Source

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:


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download