0

There is a simple command which prints the number of lines in a file.:

wc -l

When I use this command to a regular text file. It counts the lines correctly. But when I count the lines in some bash script, this command gives a value one line less than the lines in this script actually.

For example, if I'll run this script with name script.sh :

#!/bin/bash
    
echo $(wc -l $0)

In the terminal I will get the output:

2 ./script.sh

When use this command for txt-file with 5 lines I see:

5 filename.txt

Why did wc count so?

  • 6
    I'll bet the script file doesn't end with a newline. `wc` counts newlines. – Barmar Nov 11 '21 at 21:00
  • 2
    So the last line isn't being counted. – Barmar Nov 11 '21 at 21:01
  • 2
    Try `wc -l script.sh` and you should see the same thing. – Barmar Nov 11 '21 at 21:01
  • @Barmar yes, when I try wc -l script.sh i see the same thing. – Bogdan Fateev Nov 11 '21 at 21:03
  • 4
    Make sure you configure your text editor to always add a newline to the last line. – Barmar Nov 11 '21 at 21:03
  • 4
    BTW, using `echo $(somecommand)` is almost always a mistake -- the `echo` and the `$( )` mostly cancel each other (except for the possibility for some parsing weirdness in between). Just use `somecommand` directly. – Gordon Davisson Nov 11 '21 at 21:11
  • @Barmar Wow, that's right. Apparently in my Sublime this is not set up in config. I changed the file via gedit and the script gave the correct result. Thank you – Bogdan Fateev Nov 11 '21 at 21:14
  • See https://www.shellhacks.com/sublime-text-add-newline-at-eof-on-save/ – Barmar Nov 11 '21 at 21:15
  • @GordonDavisson Thanks for your comment, I will consider – Bogdan Fateev Nov 11 '21 at 21:16
  • If the purpose of the [useless `echo`](https://www.iki.fi/era/unix/award.html#echo) was to normalize spacing, the standard way to do that is to use a redirection; `wc -l <"$0"` (notice also [When to wrap quotes around a shell variable](https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable)) – tripleee Nov 12 '21 at 10:29

0 Answers0