指令使用要點
指令用途
- 查看目錄或檔案大小。
- 可以搭配 pipeline 透過 sort 指令進行排序,整理硬碟空間、找肥貓檔案的場合很好用。
- Linux 和 macOS 都支援
du
指令,指令操作原理也大同小異,只是有些 option 的字眼或支援度上略有差異。例如 linux 是--max-depth=<目錄層數>
,macOS 則是-d <目錄層數>
常用 option:
Option (Linux) | Option (Mac) | Description |
---|---|---|
--max-depth=<depth> | -d <depth> | 指定往下的目錄層數 |
-s | -s | 等於 depth=0 |
-c | -c | 最後多顯示一個 total 值 |
-h | -h | 以人眼容易閱讀的方式加上單位顯示 (若有指定 -b/-g/-k/-m 則無效) |
-b | (不支援) | 以 byte 為單位顯示 |
-g | -g | 以 GB 為單位顯示 |
-k | -k | 以 KB 為單位顯示 |
-m | -m | 以 MB 為單位顯示 |
用法範例
顯示當前目錄的總大小
$ du -sh
378M
顯示當前目錄底下各檔案資料夾的 size
$ du -sh ./*
68M ./2062
65M ./2062.zip
30M ./book_sources_example
4.0K ./dir1
4.0K ./dirRoot
0B ./empty_folder
214M ./masteringextjs5
4.0K ./test.sh
4.0K ./test123.txt
4.0K ./test2.txt
4.0K ./test3.txt
228K ./test_cpp
最後多顯示一個 total 值
$ du -shc ./*
68M ./2062
65M ./2062.zip
30M ./book_sources_example
4.0K ./dir1
4.0K ./dirRoot
0B ./empty_folder
214M ./masteringextjs5
4.0K ./test.sh
4.0K ./test123.txt
4.0K ./test2.txt
4.0K ./test3.txt
228K ./test_cpp
378M total
指定以 MB 為單位顯示
注意:無條件進位,若不足 1MB 會顯示 1,不會顯示小數。
$ du -sc -m ./*
68 ./2062
66 ./2062.zip
31 ./book_sources_example
1 ./dir1
1 ./dirRoot
0 ./empty_folder
215 ./masteringextjs5
1 ./test.sh
1 ./test123.txt
1 ./test2.txt
1 ./test3.txt
1 ./test_cpp
378 total
顯示往下最多 2 層的各目錄 size
$ du -h -d 2 .
3.5M ./2062/280
3.7M ./2062/274
4.6M ./2062/278
68M ./2062
376K ./masteringextjs5/app
380K ./masteringextjs5/.sencha
1.1M ./masteringextjs5/resources
120M ./masteringextjs5/ext
.....
4.0K ./test_cpp/.vscode
228K ./test_cpp
4.0K ./dir1
378M .
根據 size 由大到小排序
$ du -h -d 1 . | sort -hr
378M .
214M ./masteringextjs5
68M ./2062
30M ./book_sources_example
228K ./test_cpp
4.0K ./dirRoot
4.0K ./dir1
0B ./empty_folder
補充:
sort -r
是倒序顯示的意思。sort -h
是指以數字化 (numerical) 判讀排序,而非字母。例如下面是沒有指定-h
的範例:
$ du -h -d 1 . | sort -r
4.0K ./dirRoot
4.0K ./dir1
378M .
228K ./test_cpp
214M ./masteringextjs5
68M ./2062
30M ./book_sources_example
0B ./empty_folder