How Does the 'Ls' Command Work in Linux/Unix

How does the 'ls' command work in Linux/Unix?

ls doesn't fork. The shell forks and execs in order to run any command that isn't built in, and one of the commands it can run is ls.

ls uses opendir() and readdir() to step through all the files in the directory. If it needs more information about one of them it calls stat().

Any reason for using */ in command ls -d */ to list directories?

Adding the -d flag simply instructs ls to simply list directory entries rather than their contents. The * given to ls is expanded to all the entries in the current directory, both files and dirs. So ls -d * will list all entries in this directory, without expanding the subdirectories. But if you use */, then bash expands this to only include the directories in this directory. But with just ls */, all the directories will be expanded. Adding the -d flag prevents that, and you get just the directories in this directory.

Using ls to list directories and their total sizes

Try something like:

du -sh *

short version of:

du --summarize --human-readable *

Explanation:

du: Disk Usage

-s: Display a summary for each specified file. (Equivalent to -d 0)

-h: "Human-readable" output. Use unit suffixes: Byte, Kibibyte (KiB), Mebibyte (MiB), Gibibyte (GiB), Tebibyte (TiB) and Pebibyte (PiB). (BASE2)

How to combine ls and cd commands in Unix


cd "$(ls -trh | tail -1)"

This uses the output of the the ls|tail pipeline as the command-line arguments to cd.

EDIT: camh is correct that this should give better performance, because head won't go through the lines you're ignoring.

cd "$(ls -th | head -1)"

Unix pipe into ls

To do that you need xargs:

which studio | xargs ls -l

From man xargs:

xargs - build and execute command lines from standard input

To fully understand how pipes work, you can read What is a simple explanation for how pipes work in BASH?:

A Unix pipe connects the STDOUT (standard output) file descriptor of
the first process to the STDIN (standard input) of the second. What
happens then is that when the first process writes to its STDOUT, that
output can be immediately read (from STDIN) by the second process.



Related Topics



Leave a reply



Submit