When working with vi/vim, displaying line numbers is crucial for debugging, code navigation, and collaborative editing. While most developers know how to toggle line numbers within the editor, fewer realize you can enable them directly from the command line - saving valuable time during frequent file operations.
The conventional method involves opening the file first and then executing vim commands:
:set number # Enable line numbers :set nonumber # Disable line numbers
Vim actually provides multiple ways to enable line numbering during launch:
Method 1: Using + Argument
The most direct approach combines the file opening command with vim instructions:
vim +"set number" filename.txt
Method 2: Alternate Syntax
This equivalent syntax might be preferable in some environments:
vim -c "set number" filename.txt
Method 3: Combining with Line Navigation
You can simultaneously jump to a specific line while enabling numbers:
vim +"set number" +10 filename.txt # Opens at line 10 with numbers
For persistent line numbering across sessions, consider these alternatives:
Creating .vimrc Settings
Add these lines to your ~/.vimrc for automatic numbering:
set number set relativenumber # For relative line numbers
Environment Variable Approach
For temporary session-specific settings:
VIMINIT='set number' vim filename.txt
Here are real-world use cases combining line numbers with other operations:
# Debugging: Open with numbers and search for error vim +"set number" +"/error" app.log # Code Review: Compare files side-by-side with numbers vim -O +"set number" file1.py file2.py # System Administration: View logs with persistent numbering alias vimlog='vim +"set number" +"set nowrap"'
If line numbers aren't appearing as expected:
- Verify you're using vim (not original vi) with
vim --version
- Check for conflicting settings in ~/.vimrc or /etc/vimrc
- Try the minimal test case:
vim -u NONE +"set number" filename
When working with Vi or Vim, displaying line numbers is essential for debugging and navigation. While most users know how to toggle line numbers within the editor (:set number
), fewer are aware of command-line options to enable this feature immediately at launch.
You can start Vim with line numbers displayed by using the -c
flag to execute commands on startup:
vim -c "set number" filename.txt
For those who prefer a more concise format, Vim accepts this equivalent syntax:
vim +"set number" filename.txt
You can combine line numbers with jumping to a specific line number:
vim +"set number" +10 filename.txt # Opens at line 10 with numbers
For frequent use, add this to your .vimrc
file:
set number
For relative line numbers (useful for navigation), use:
vim -c "set relativenumber" filename.txt
When opening multiple files with line numbers:
vim -c "set number" file1.txt file2.txt
Remember that command-line options are temporary. For permanent line numbers, modify your .vimrc
as shown above.