คำสั่งค้นหา Directory ที่ใช้พื้นที่มากที่สุด 100 อันดับบน Linux

เครื่อง laptop ผมซึ่งใช้ Ubuntu Linux นั้น เนื้อที่ว่างบน HDD กำลังร่อยหรอ ลงไปทุกที วันนี้มีเวลาว่าง จึงอยากจะหาว่า Directory อะไรบ้างที่ใช้เนื้อที่เยอะ ๆ ก็เลยเขียน คำสั่งบน Bash Shell ได้ ดังนี้

$ sudo du -m  / | sort -rn | head -100 > ~/disk_usage.txt &

จะเห็นว่า คำสั่งดังกล่าวเป็นการรวมกันจาก 3 คำสั่งแล้ว ผลลัพธ์ที่ได้จากโปรแกรมหนึ่งจะถูกส่ง (pipe) ไปเป็นอินพุทให้กับอีกโปรแกรมหนึ่ง

คำสั่งแรก คือ sudo du -m คำสั่ง du (disk usage) เป็นคำสั่งที่ใช้หาพื้นที่การใช้งานของแต่ละ directory ที่ต้องส่ง option -m เพื่อให้แสดงหน่วยของพื้นที่เป็น MB และใช้ sudo เพื่อ execute คำสั่ง du ด้วยสิทธิ์ของ root เพื่อที่จะเข้าไปได้ในทุก ๆ directory

คำสั่งที่สอง คือ sort -rn คำสั่ง sort เป็นคำสั่งใน shell ที่ใช้ในการเรียงข้อมูล เนื่องจากผลลัพธ์ที่ได้จาก du นั้น colum แรกของแต่ละบรรทัดจะเป็นการแสดงพื้นที่เป็นตัวเลขในหน่วย MB ผมจึงต้องใช้ option -rn ของคำสั่ง sort เพื่อให้เรียงข้อมูลแบบตัวเลข (-n) และ เรียงข้อมูลจากมากไปน้อย (-r)

คำสั่งที่สุดท้าย คือ head -100 > ~/disk_usage.txt คำสั่ง head เป็นคำสั่งใน shell ที่ใช้ในการดูข้อมูลตอนต้นของไฟล์ option -100 หมายถึง แสดงเฉพาะ 100 บรรทัดแรกของไฟล์ ในคำสั่งนี้ผมยังได้ทำการ redirect ผลลัพธ์ที่ได้เพื่อบันทึกลงไฟล์ที่ชื่อว่า disk_usage.txt ซึ่งจะอยู่ใน home directory ของผม อีกด้วย

หมายเหตุ: ที่ผมใส่เครื่องหมาย & ที่ท้ายคำสั่งเพราะว่าคำสั่งนี้ใช้เวลานานมากผมจึงสั่งให้ execute คำสั่งดังกล่าวในลักษณะเป็น background process

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd><img> <object> <embed> <param>
  • Lines and paragraphs break automatically.
  • Images can be added to this post.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Copy the characters (respecting upper/lower case) from the image.
ญาณรักข์ วรรณสาย