Bash File Line Count Comparing to Integer Incorrectly

28 Views Asked by At

I have a simple bash script where I'm trying to iterate over the lines in a text file and calculate different metrics (moving average, derivative, etc). I'm having some trouble comparing the index iterator with the total line count and is producing some unexpected results.

input="sample.txt"
lines= wc -l < $input # 14
x=1
[[ ${x} -lt ${lines} ]] && echo "true" || echo "false"

^This Returns False (when comparing 1 < 14 )

Therefore this while loop doesn't run:

while [[ ${x} -lt ${lines} ]]
do
  echo "Welcome $x times"
  read p
  echo $p
  x=$(( $x + 1 ))
done < $input
1

There are 1 best solutions below

0
Joshua Wilkinson On

As mentioned by @GordonDavisson, I was not using the proper syntax for assigning the output of a command to a variable so instead of lines= wc -l < $input, using lines=$(wc -l < $input) provides the expected result.