dirs Command

The dirs command displays the directory stack, which is a list of directories maintained by the shell. It works with pushd and popd commands for efficient directory navigation.

Syntax

dirs [+N | -N] [-clpv]

Description

The dirs command displays the list of currently remembered directories. Directories are added to the list with the pushd command and removed with the popd command. The current directory is always at the top of the stack.

Key features:

  • Displays the directory stack
  • Shows numbered directory positions
  • Works with pushd and popd
  • Supports various display formats
  • Built-in shell command

Common Options

Option Description
+N Display the Nth directory (counting from left, starting with 0)
-N Display the Nth directory (counting from right, starting with 0)
-c Clear the directory stack
-l List directories with full pathnames
-p Print directories one per line
-v Print directories with their stack positions

Examples

Display directory stack

dirs

Shows all directories in the stack

Display with full pathnames

dirs -l

Shows directories with complete paths (no ~ expansion)

Display one directory per line

dirs -p

Lists each directory on a separate line

Display with position numbers

dirs -v

Shows directories with their stack position numbers

Display specific directory by position

dirs +1

Shows the directory at position 1 (second from left)

Display directory from right

dirs -0

Shows the rightmost directory (last in stack)

Clear directory stack

dirs -c

Removes all directories from the stack except current

Complete directory stack workflow

# Start in home directory pwd /home/user # Push some directories pushd /var/log pushd /etc pushd /tmp # Display the stack dirs /tmp /etc /var/log /home/user # Display with positions dirs -v 0 /tmp 1 /etc 2 /var/log 3 /home/user # Display one per line dirs -p /tmp /etc /var/log /home/user

Complete example showing directory stack operations

Working with pushd and popd

# Push directories onto stack pushd /usr/local pushd /opt # View stack dirs /opt /usr/local /home/user # Pop back to previous directory popd /usr/local /home/user # View updated stack dirs /usr/local /home/user

Example of using dirs with pushd and popd

Directory Stack Concepts

  • Stack Structure: Last In, First Out (LIFO) data structure
  • Position 0: Always the current directory (top of stack)
  • Left to Right: Position 0, 1, 2, 3... (newest to oldest)
  • Right to Left: Position -0, -1, -2, -3... (oldest to newest)
  • Persistence: Stack persists within the shell session

Common Use Cases

  • Project Navigation: Quickly switch between project directories
  • System Administration: Navigate between configuration directories
  • Development: Switch between source, build, and test directories
  • File Management: Remember frequently accessed locations
  • Backup Operations: Track multiple backup locations

See also