2

I need to count the number of lines in a file and then send a message depending if the number of lines is less than or equal to 20. I am trying to do it this way:

touch file.txt
echo "hello" > file.txt
nr_lines = $(wc -l < file.txt)
if[$nr_lines -le 20]; then
  echo "number of lines is less than 20."
fi

But it does not work. What am I doing wrong?

João Dias
  • 45
  • 1
  • 8
  • 2
    `-le` means "less than or equal to" so the message "number of lines is less than 20" generally is not correct. – Abelisto Mar 23 '20 at 17:33
  • 1
    https://stackoverflow.com/questions/2268104/command-not-found-error-in-bash-variable-assignment/2268117#2268117 – William Pursell Mar 23 '20 at 17:38
  • 1
    Use https://www.shellcheck.net/ on all your shell scripts. – Benjamin W. Mar 23 '20 at 17:48
  • 1
    The short answer is that you need a space after `[` and before `]`. You should know that as a bash improvement, the `[[` and `]]` syntax was added for these conditional statements. So, try this: `[[ nr_lines -le 20 ]]` - you can even do away with the `$` in the `[[ ]]` test. – Mark Mar 23 '20 at 21:06

3 Answers3

3
nr_lines = $(wc -l < file.txt)
if[$nr_lines -le 20]; then

This should be:

nr_lines=$(wc -l < file.txt)
if [ $nr_lines -le 20 ]; then

I'd use awk though.

awk 'NR>=20{exit} END{if(NR<20)print "number of lines is less than 20"}' file.txt
oguz ismail
  • 1
  • 16
  • 47
  • 69
1

You are doing a lot right! There are just a few syntax errors in your code that make it not work.

  1. Bash does not like spaces in variable assignments
    • Changed nr_lines = $(wc -l < file.txt) to nr_lines=$(wc -l < file.txt)
  2. Bash LOVES spaces when it comes to boolean operators though! :)
    • Changed [$nr_lines -le 20] to [ $nr_lines -le 20 ]
touch file.txt
echo "hello" > file.txt
nr_lines=$(wc -l < file.txt)
if [ $nr_lines -le 20 ]; then
  echo "number of lines is less than 20."
fi

When things in bash don't work the silly syntax errors are often:

  • Add/Remove spaces somewhere
  • Mixup with ' and " and `
  • Forgot to escape a special character
Lenna
  • 1,220
  • 6
  • 22
0

The following is safer

nr_lines=$(wc -l < file.txt)
if [[ ${nr_lines} -le 20 ]]; then
   echo "number of lines is less than 20."
fi
Rahav
  • 1,755
  • 15
  • 18