如何在Linux中查看文件和目录的大小?如果使用df -m,那么它会显示所有目录在顶层的大小,但是,对于目录内的目录和文件,我如何检查大小?


当前回答

文件使用ls命令,目录使用du命令。

检查文件大小

ls -l filename   #Displays Size of the specified file
ls -l *          #Displays Size of All the files in the current directory
ls -al *         #Displays Size of All the files including hidden files in the current directory
ls -al dir/      #Displays Size of All the files including hidden files in the 'dir' directory

Ls命令不会列出目录的实际大小(为什么?)为此,我们使用du。

检查目录大小

du -sh directory_name    #Gives you the summarized(-s) size of the directory in human readable(-h) format
du -bsh *                #Gives you the apparent(-b) summarized(-s) size of all the files and directories in the current directory in human readable(-h) format

在上述任何命令中包含-h选项(例如:ls -lh *或du -sh)将以人类可读的格式给出大小(kb, mb,gb,…)

有关更多信息,请参阅man ls和man du

其他回答

你可以在Linux中使用ls -sh,也可以进行排序 你需要去目录,在那里你想检查文件的大小

您必须区分文件大小和磁盘使用情况。两者之间的主要区别在于文件被“切割成碎片”并存储在块中。

现在的块大小是4KiB,所以文件将使用4KiB的多个磁盘空间,不管它们有多小。

如果你使用stat命令,你可以看到两个数字并排。

stat file.c

如果您想要一个更紧凑的目录视图,您可以使用ls -ls,这将为您提供1KiB单位的使用量。

ls -ls dir

du也会给出真实的磁盘使用情况,单位为1KiB,或者带有-u标志的dutree。

例如:1字节文件的使用情况

$ echo "" > file.c

$ ls -l file.c
-rw-r--r-- 1 nacho nacho 1 Apr 30 20:42 file.c

$ ls -ls file.c
4 -rw-r--r-- 1 nacho nacho 1 Apr 30 20:42 file.c

$ du file.c
4 file.c

$ dutree file.c
[ file.c 1 B ]

$ dutree -u file.c
[ file.c 4.00 KiB ]

$ stat file.c
 File: file.c
 Size: 1 Blocks: 8 IO Block: 4096 regular file
Device: 2fh/47d Inode: 2185244 Links: 1
Access: (0644/-rw-r--r--) Uid: ( 1000/ nacho) Gid: ( 1000/ nacho)
Access: 2018-04-30 20:41:58.002124411 +0200
Modify: 2018-04-30 20:42:24.835458383 +0200
Change: 2018-04-30 20:42:24.835458383 +0200
 Birth: -

此外,在现代文件系统中,我们可以使用快照、稀疏文件(其中有漏洞的文件),这进一步使情况复杂化。

您可以在本文中了解更多细节:了解Linux中的文件大小

进入所选目录并执行:

$ du -d 1 -h

地点:

-d 1 is the depth of the directories

-h is the human-readable option

你会看到:

0   ./proc
8.5M    ./run
0   ./sys
56M ./etc
12G ./root
33G ./var
23M ./tmp
3.2G    ./usr
154M    ./boot
26G ./home
0   ./media
0   ./mnt
421M    ./opt
0   ./srv
2.6G    ./backups
80G .

如果您在脚本中使用它,请使用stat。

$ date | tee /tmp/foo
Wed Mar 13 05:36:31 UTC 2019

$ stat -c %s /tmp/foo
29

$ ls -l /tmp/foo
-rw-r--r--  1 bruno  wheel  29 Mar 13 05:36 /tmp/foo

这将给出以字节为单位的大小。有关更多输出格式选项,请参阅man stat。

OSX/BSD的等效版本是:

$ date | tee /tmp/foo
Wed Mar 13 00:54:16 EDT 2019

$ stat -f %z /tmp/foo
29

$ ls -l /tmp/foo
-rw-r--r--  1 bruno  wheel  29 Mar 13 00:54 /tmp/foo

您所需要的只是-l和——block-size标志

工作目录下所有文件和目录的大小(以mb为单位)

ls -l --block-size=M

工作目录下所有文件和目录的大小(单位:gb)

ls -l --block-size=G

指定文件或目录的大小

ls -l --block-size=M my_file.txt
ls -l --block-size=M my_dir/

ls——帮助 -l使用长列表格式 ——block-size=SIZE:在打印之前按SIZE缩放大小;例如, '——block-size=M'以。为单位打印大小 1048576个字节;参见下面的SIZE格式 “SIZE”为可选单位,取值为整型。例如:10M为10*1024*1024。 单位为K, M, G, T, P, E, Z, Y(1024的幂)或KB, MB,… (1000的幂)。