When you are debugging a broken script, reviewing a massive configuration file, or communicating with another developer, referencing line numbers is essential. Saying “there is a syntax error on line 42” is incredibly precise. However, standard Linux tools like cat or less do not display line numbers by default, making it difficult to find the exact location of an issue. While you can open the file in a text editor like nano or vi to see line numbers, there is a dedicated, lightweight utility for this exact purpose: the nl (Number Lines) command.
Basic Usage of the nl Command
The nl command functions exactly like the cat command—it reads the contents of a file and prints it directly to your terminal screen—but it automatically prepends a sequential number to the beginning of every line.
- Open your Linux terminal.
- Type the command followed by the filename:
nl /etc/fstab - Press Enter.
The output will look something like this:
1 # /etc/fstab: static file system information.
2 #
3 UUID=12345678-1234 / ext4 errors=remount-ro 0 1
4 UUID=87654321-4321 none swap sw 0 0
Handling Blank Lines
By default, the nl command is intelligent: it only numbers lines that actually contain text. If your script has three blank lines in a row for visual spacing, nl will skip over them, meaning your numbering will not match the absolute line numbers you would see in a text editor like VS Code.
To force nl to number absolutely every single line in the file, including blank empty lines, you must use the -b (body numbering) flag and set it to a (all).
nl -b a script.sh
Now, even the blank lines will receive a sequential number on the far left edge of the screen.
Formatting the Numbers
If you are using nl to prepare a file for printing or formal documentation, you might not like the default formatting, which right-justifies the numbers and uses a massive blank space to separate the number from the text.
You can change the number formatting using the -n (number format) flag. The three options are:
ln(Left justified, no leading zeros)rn(Right justified, no leading zeros — this is the default)rz(Right justified, with leading zeros)
To make the output look like a classic piece of source code with leading zeros, you would run:
nl -n rz script.sh
This will change the output so the numbers look like 000001, 000002, etc., keeping the text perfectly aligned regardless of how many lines are in the file.