How to Save and Exit Files in Bash Vi/Vim Editor: Essential Commands for Linux Users


2 views

When you type edit filename in bash, you're likely using either vi or vim (Vi IMproved). Most modern Linux distributions, including SUSE Enterprise 11, use vim as the default editor. To confirm, run:

which vi

This typically returns /usr/bin/vi, which is often a symlink to vim.

Vi/vim has different modes:

  • Normal mode: For navigation and commands (press ESC to enter)
  • Insert mode: For text editing (press i to enter)
  • Command-line mode: For saving/quitting (press : in Normal mode)

To save and exit a file:

1. Press ESC (ensure you're in Normal mode)
2. Type :wq
3. Press Enter

Alternative commands:

:w      # Save without exiting
:q      # Quit if no changes
:q!     # Quit without saving changes
:x      # Save and quit (same as :wq but only saves if changes were made)

If ESC isn't working when connecting via SSH from Mac:

  1. Try pressing ESC twice
  2. Wait a second after pressing ESC before entering commands
  3. Check your terminal settings (iTerm2/Terminal.app may need configuration)
  4. Try using Ctrl+[ as an alternative to ESC

For power users:

:w newfilename  # Save as new file
:saveas path/to/file  # Save to specific location
ZZ              # Quick save and exit (Normal mode)
:e!             # Revert to last saved version

Add these lines to ~/.vimrc:

set nocompatible   # Disable vi compatibility
set backspace=indent,eol,start  # Allow backspacing over everything
syntax on          # Enable syntax highlighting
set number         # Show line numbers

If you prefer a simpler editor:

nano filename     # User-friendly alternative
emacs filename    # Another popular option

To change your default editor:

export EDITOR=nano   # Add to ~/.bashrc to make permanent

When you type edit filename in bash on most Linux systems (including SUSE Enterprise 11), you're typically launched into the vi or vim editor. This can be confusing for beginners coming from graphical editors.

The key to working with vi is understanding its modal nature:

1. Command mode (default when opening)
2. Insert mode (for actual editing)
3. Last-line mode (for commands)

Here's the complete sequence to save and exit:

1. Press ESC to ensure you're in command mode
2. Type : (colon) to enter last-line mode  
3. Type one of these commands:
   - wq (write and quit)
   - x (same as wq)
   - q! (quit without saving)
4. Press Enter

If you're stuck:

- If ESC doesn't work, try Ctrl+[ 
- If you see "-- INSERT --" at bottom, you're in insert mode
- If you get "E37: No write since last change", use :wq! to force

For quick edits, you can use these bash alternatives:

# Using nano (more beginner-friendly)
nano filename

# Using printf (for simple edits)
printf "new content" > filename

Add this to your ~/.bashrc if you prefer nano:

export EDITOR=nano
export VISUAL=nano