Shell Script that reads a file

I have below script to read a file line by line. How can I ensure that the loop will stop after last line.

 #!/bin/bash
 while read -r mod ver tarball; do     
    echo $mod 
done < taskfile.txt

Why wouldn't it stop after the last line?

Do you think that whatever interpreter is running your script is going to add phantom lines to your input file when it hits end-of-file?

(Note that when #!interpreter does not start in the 1st character of the 1st line of your script, it has no effect on what interpreter will be invoked by your operating system to run your script and is just treated as a [misleading] comment.)

while executes commands as long as a test succeeds.

read will not succeed at EOF from taskfile.txt and the loop will stop.

if the last line is not in fact a line (it doesn't end with \n), then you will reach EOF before read reaches the delimiter. An example:

mute@zbox:~$ printf '1\n2\n3' > file
mute@zbox:~$ while read -r a b c; do echo "$a"; done < file
1
2
mute@zbox:~$

Text files by definition should end with a newline, but if this is the problem you need to work around you can try entering your loop again with a test like this:

mute@zbox:~$ while read -r a b c || [[ $a ]]; do echo "$a"; done < file
1
2
3

Thanks for the reply.

Will it not be an endless loop if I will not put a counter to it? Or an end of file flag?

No! After the last line in your file is read, the next read will report that it found end-of-file. No special flags are needed. When you read from a regular file, and no more data is available, the read() system call will return 0 (no data available). When you read from a pipe and no more data is available at that moment, the read() system call will hang until more data is available (in which case it will return the data available at that time or the number of bytes requested, whichever is smaller) or all file descriptors open for writing to that pipe have been closed (in which case it will return 0).

The operating system knows how big a file is and won't return more data to the user than what exists in the file.