ls sort in linux

In Linux, the ls command lists directory contents, and you can sort the output using various options. Here are some common ways to sort the output of the ls command:

  1. Sort by name (default):
    Alphabetically sorts the files and directories by name. This is the default behavior of ls.
   ls
  1. Sort by modification time:
    Sorts the files and directories by modification time, with the newest files first.
   ls -lt
  1. Sort by size:
    Sorts the files by size, largest first.
   ls -lS
  1. Reverse sort:
    Reverses the sort order of the previous option. For example, with -lS, it will sort from largest to smallest.
   ls -lSr
  1. Sort by extension:
    This isn’t a built-in ls option, but you can use sort with ls to sort by file extension.
   ls -l | sort -k 2
  1. Sort by status change time:
    Sorts by the time of the last status change.
   ls -lc
  1. Sort by version:
    This is not a direct ls option, but you can sort by version number by using sort with a custom key.
   ls -l | sort -V
  1. Sort by inode number:
    Sorts by inode number, which is useful for seeing which files are hard links to each other.
   ls -li
  1. Combining sort options:
    You can combine options to customize the sort. For example, to sort by modification time and then by name:
   ls -lt | sort -k 6,7

Remember that some of these options require a long listing format (-l) to be effective, as they sort based on the detailed information provided in the long listing format.

Also, the --sort option can be used with ls in some systems to specify the sort order directly, like --sort=time for modification time or --sort=size for file size.

Please note that the exact behavior of ls can vary between different Unix-like systems, as the command can be customized or overridden by the system’s configuration.

This entry was posted in Linux File & Directory, Linux Ls and tagged , , . Bookmark the permalink.