乐闻世界logo
搜索文章和话题

How to use ls to list directories and their total size?

1个答案

1

In Unix-like systems, the ls command is primarily used to list files and subdirectories within a directory. However, the ls command itself does not inherently display the total size of the directory. To obtain the total size of a directory and its contents, you can use the du command, often combined with the ls command to retrieve more detailed file listings.

For example, if you want to view the total size of a directory along with the sizes of each subdirectory and file, you can use the following command:

bash
du -sh *

The options are explained as follows:

  • du stands for disk usage and is used to check disk space consumption for files and directories.
  • -s summarizes the size for each parameter without listing detailed sizes of subdirectories.
  • -h displays sizes in a human-readable format (e.g., KB, MB, GB).

If you need to simultaneously obtain a list of files and directories along with their respective sizes, you can combine ls and du as follows:

bash
ls -lh

In this command:

  • ls is an abbreviation for list and is used to display directory contents.
  • -l provides output in a long format, including permissions, owner, and size details.
  • -h displays file sizes in a human-readable format, consistent with the previous option.

To view a detailed list of all files and directories, including hidden files (those starting with a dot), use the -a option:

bash
ls -lah

This will list all files, including hidden ones.

Practical Application Example:

Suppose you are a server administrator who needs to check the sizes of each log file within the /var/log directory and the total disk space used by logs. You might use:

bash
cd /var/log du -sh ls -lh

This allows you to quickly understand the total space occupied by log files and the specific sizes of each log file, enabling you to manage them effectively—such as archiving old logs or cleaning up unnecessary log files.

2024年8月14日 18:06 回复

你的答案