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


当前回答

这是du命令。

目录和/或文件的大小,以一种人性化的方式:

$ du -sh .bashrc /tmp

我把它当成一个不存在的英语单词来记忆。


——-size命令行开关使它测量表观大小(ls显示的),而不是实际的磁盘使用量。

其他回答

要获得目录的总大小或文件使用的总大小,

du -csh <directory or filename*> | grep total

这是du命令。

目录和/或文件的大小,以一种人性化的方式:

$ du -sh .bashrc /tmp

我把它当成一个不存在的英语单词来记忆。


——-size命令行开关使它测量表观大小(ls显示的),而不是实际的磁盘使用量。

文件使用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

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

现在的块大小是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 -sh backup-lr-May-02-2017-1493723588.tar.gz

NB:

-s, --summarize
            display only a total for each argument
-h, --human-readable
            print sizes in human readable format (e.g., 1K 234M 2G)