0

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
Joshua Wilkinson
  • 133
  • 2
  • 10
  • 1
    That's the wrong syntax for assigning the output of a command (`wc`) to a variable (`lines`); see ["How do I set a variable to the output of a command in Bash?"](https://stackoverflow.com/questions/4651437/how-do-i-set-a-variable-to-the-output-of-a-command-in-bash). Also, run your code through [shellcheck.net](https://www.shellcheck.net) and fix the other problems it points out. If it still doesn't work as expected, put `set -x` before the problem to get an execution trace, and see what that indicates. – Gordon Davisson Sep 23 '22 at 20:50
  • Hi @GordonDavisson, thanks for sending that link! That was actually the solution to my problem, lines=$(wc -l < $input) properly sets the variable – Joshua Wilkinson Sep 24 '22 at 02:03

1 Answers1

0

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.

Joshua Wilkinson
  • 133
  • 2
  • 10