du (disk usage)
The du (disk usage) command is a powerful tool for measuring the amount of disk space used by files and directories. This command is essential for system administrators and users who need to monitor disk utilization effectively.
Understanding the Syntax
The basic syntax of the du command is:
du [OPTIONS]... [FILE]...
Where [OPTIONS] can be replaced with various flags to modify the command's behavior, and [FILE]... specifies the files or directories to analyze. If no file or directory is specified, du will report the disk usage of the current directory.
Key Options
Here are some of the key options available with the du command:
Examples
1. Tracking Disk Usage by File Type
One can use du along with other commands like find to track disk usage by specific file types. For example, to find out how much space all .log files consume in a directory, you can use:
find /path/to/directory -type f -name "*.log" -exec du -ch {} +
This command finds all .log files and calculates their disk usage in a human-readable format, culminating in a total.
2. Comparing Disk Usage in Multiple Directories
To compare disk usage across multiple directories without going into subdirectories, use:
du -sh /path/to/directory1 /path/to/directory2
It is useful for a quick comparison of directory sizes.
3. Excluding Specific Directories or Files
You can exclude specific directories or files from the du output to focus on the relevant data. For example:
du -h --exclude='*.tmp' /path/to/directory
This command skips files ending in .tmp when calculating disk usage.
4. Integrating du with awk for Conditional Reporting
Using du in combination with awk can help you filter outputs based on size conditions. For example, to find directories larger than 1GB:
du -h /path/to/directory | awk '$1 ~ /G$/ {print}'
5. Scripting with du for Regular Monitoring
du can be scripted to provide regular reports on disk usage. For instance, a cron job can be set up to run a script that checks disk usage and sends an alert if usage exceeds a certain threshold.
#!/bin/bash
usage=$(du -s /path/to/directory | cut -f 1)
if [ $usage -gt 1000000 ]; then
message="Disk usage has exceeded limit"
curl -s -X POST "https://api.telegram.org/botYOUR_BOT_TOKEN/sendMessage" -d chat_id=-YOUR_GROUP_CHAT_ID -d text="$message"
fi
This script uses du to get the total size of a directory and sends a message alert to the preconfigured telegram group if the size exceeds 1GB.