Bash: How to Get the Last Line of a File


Often you may want to use Bash to get the last line of a particular file.

You can use the following syntax to do so:

tail -n 1 coaches.txt

This particular example will display the last line in the file named coaches.txt.

If you’d like, you can use the following syntax to store the last line of the file in a variable:

last_line=$( tail -n 1 coaches.txt )

This particular example will store the last line of the coaches.txt file in a variable named last_line.

Here is what the various commands do:

  • tail: Outputs the last line of a file
  • -n: Specifies the number of last lines in the file to output

The following example shows how to get the last line of a file in practice.

Example: How to Get the Last Line of a File in Bash

Suppose that we have a file named coaches.txt.

We can use the cat command to view the contents of this file:

Suppose that we would like to display only the last line of this file.

We can use the following syntax to do so:

tail -n 1 coaches.txt

The following screenshot shows how to use this syntax in practice:

Bash get last line of file

Notice that only the last line of the file is displayed.

Note that we can also use the following syntax to store this last line in a variable named last_line:

last_line=$( tail -n 1 coaches.txt )

The following screenshot shows how to use this syntax in practice:

Bash store last line of file in variable

Notice that when we use the echo command to display the value of this variable we can see that the variable contained the last line of the file.

Also note that if we’d like to display the last n lines of a file, we can simply change the number after the -n command in the syntax.

For example, we can use the following syntax to display the last 3 lines in the file:

tail -n 3 coaches.txt

The following screenshot shows how to use this syntax in practice:

Bash display last n lines in file

Notice that only the last 3 lines of the file are displayed.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Find Duplicate Lines in File
Bash: How to Delete All Empty Lines in File
Bash: How to Count Number of Unique Lines in File

Leave a Reply