Reversing directory listings in Linux helps quickly spot items at the end of an alphabetical list or flip the usual view of files. This is useful when scanning long directory listings, checking tail entries, or comparing output with scripts or other tools that assume a particular order.

The ls command controls how directory entries are displayed, including sorting by name, modification time, or size. Options such as -r for reverse order and -t for time-based sorting change only the presentation of entries, without modifying the files themselves. Combining these options produces reverse alphabetical listings, newest-to-oldest views, or other useful layouts.

Choosing between built-in ls options and external tools such as sort depends on how much control is needed over the ordering. Large directories, locale-specific collation, and scripts that parse ls output can be affected by sort options, so ordering should be chosen carefully to keep command behavior predictable.

Steps to reverse directory listing in Linux:

  1. Open a terminal on the Linux system.
    $ whoami
    root
  2. Display directory contents in the default alphabetical order.
    $ ls /root/sg-work/reverse-demo
    first.log
    second.log
    third.log
  3. Reverse the alphabetical order using the -r option.
    $ ls -r /root/sg-work/reverse-demo
    third.log
    second.log
    first.log

    The -r option reverses the current sort order without changing the primary sort criterion.

  4. List files sorted by modification time, newest first, using -t.
    $ ls -lt /root/sg-work/reverse-demo
    total 12
    -rw-r--r-- 1 root root 6 Dec 22  2025 third.log
    -rw-r--r-- 1 root root 7 Dec 22  2025 second.log
    -rw-r--r-- 1 root root 6 Dec 22  2025 first.log
  5. Show files sorted by modification time in reverse (oldest first) using -lrt.
    $ ls -lrt /root/sg-work/reverse-demo
    total 12
    -rw-r--r-- 1 root root 6 Dec 22  2025 first.log
    -rw-r--r-- 1 root root 7 Dec 22  2025 second.log
    -rw-r--r-- 1 root root 6 Dec 22  2025 third.log

    The combination -l, -t, and -r shows detailed information, sorts by modification time, and reverses that order.

  6. Use sort -r in a pipeline when a reverse ordering is needed after additional processing.
    $ ls -1 /root/sg-work/reverse-demo
    first.log
    second.log
    third.log
    
    $ ls -1 /root/sg-work/reverse-demo | sort -r
    third.log
    second.log
    first.log

    Using ls -1 with sort provides one entry per line, which is convenient for further text processing and scripting.

Discuss the article:

Comment anonymously. Login not required.