Home Linux How to Show Line Numbers in Vi

How to Show Line Numbers in Vi

by admin

When making changes to scripts or text files from the Linux command line I tend to use Vi / Vim as my go to editor as it tends to be available on any Linux system I work on.

If you’re used to writing scripts using a tool such as vscode, you will be used to seeing line numbers in the editor. Line numbers are particularly useful when writing scripts as a way to help navigate your code making it easier to debug scripts as well as work collaboratively. When first using vi or vim, they are a notable absence, as by default they are not shown. Luckily it’s easy to turn line numbering on.

Read on to find out how to show line numbers in vi.

How to Turn on Line Numbers in Vi

There are a few options to be aware of around line numbers in vi. We’ll start with the most straight forward, which is known as absolute line numbering.

As mentioned earlier, by default vi or vim doesn’t display line numbers. Let’s take a look at a terraform file in vi:

$ vi main.tf
provider "aws" {
  version = "~> 2.0"
  access_key = var.access_key
  secret_key = var.secret_key
  region     = var.region
}

resource "aws_key_pair" "mykeypair" {
  key_name   = "myec2keypair"
  public_key = file("id_rsa.pub")
}

No line numbers! Let’s turn them on. First, press the ESC key to switch to vi’s command mode. At the prompt type:

:set number

Then hit the return key – line numbers should immediately appear!

  1 provider "aws" {
  2   version = "~> 2.0"
  3   access_key = var.access_key
  4   secret_key = var.secret_key
  5   region     = var.region
  6 }
  7
  8 resource "aws_key_pair" "mykeypair" {
  9   key_name   = "myec2keypair"
 10   public_key = file("id_rsa.pub")
 11 }

This also works is you use :set nu :

:set nu

How to Turn Off Line Numbers in Vi

You can turn line numbers off in vi by using either of the following:

:set nonumber
:set nonu

Adding no has the effect of turning off the number flag enabled earlier.

Now, these commands will let you turn line numbering on and off, but only interactively and for the session you are in. Luckily, there is a way to set the behaviour permanently.

Enable Line Numbering in Vi Permanently

To enable line numbers in Vi or Vim so that they are turned on every time you can set the option in the .vimrc configuration file.

To do so, open .vimrc in your favourite text editor:

$ vi ~/.vimrc

Then add the following line:

:set number

Save and close the file. Next time you launch Vi you should see that line numbering is enabled!

Final Thoughts

In this article you have learned how to show line numbers in vi by using the  :set number command. We then looked at how to make the setting stick by adding it to the .vimrc configuration file.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More