Issue
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?
Solution
You are doing a lot right! There are just a few syntax errors in your code that make it not work.
- Bash does not like spaces in variable assignments
- Changed
nr_lines = $(wc -l < file.txt)
tonr_lines=$(wc -l < file.txt)
- Changed
- Bash LOVES spaces when it comes to boolean operators though! :)
- Changed
[$nr_lines -le 20]
to[ $nr_lines -le 20 ]
- Changed
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
Answered By - Lenna Answer Checked By - Senaida (WPSolving Volunteer)