-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathhow-big
More file actions
executable file
·76 lines (62 loc) · 1.95 KB
/
how-big
File metadata and controls
executable file
·76 lines (62 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#!/usr/bin/env bash
set -euo pipefail
# Note: we still allow partial results when permission errors occur on some
# entries. We capture non-zero exits from find/du as "partial" rather than
# failing the script, but keep pipefail to catch genuine pipeline issues.
SCRIPT_NAME=$(basename "$0")
usage() {
cat <<EOF
Usage: $SCRIPT_NAME [-a] [directory]
Displays the size of files and subdirectories in the specified directory,
sorted in descending order by size.
If no directory is provided, the current working directory is used.
Options:
-a Show individual file sizes in addition to directories
-h, --help Show this help message and exit
Examples:
$SCRIPT_NAME ~/.local/share
sudo $SCRIPT_NAME
$SCRIPT_NAME .
$SCRIPT_NAME -a /home/user
EOF
exit 0
}
# Default behavior (show directories only)
SHOW_FILES="false"
# Parse command-line arguments
while [[ $# -gt 0 ]]; do
case "$1" in
-a) SHOW_FILES="true" ;; # Enable file size display
-h | --help) usage ;; # Show help and exit
*) TARGET_DIR="$1" ;; # Assume anything else is the directory argument
esac
shift
done
# Default to the current directory if no path is given
TARGET_DIR="${TARGET_DIR:-.}"
# Ensure the given path exists and is a directory
if [[ ! -d $TARGET_DIR ]]; then
echo "Error: '$TARGET_DIR' is not a valid directory." >&2
exit 1
fi
# Run the disk usage command with optional file inclusion
DU_TMP=$(mktemp)
partial=false
trap 'rm -f "$DU_TMP"' EXIT
if [[ "$SHOW_FILES" == "true" ]]; then
# Cross-platform: use find + du for files, then du for directories
if ! find -- "$TARGET_DIR" -maxdepth 1 -type f -exec du -h {} + >>"$DU_TMP" 2>/dev/null; then
partial=true
fi
if ! du -h -d 1 -- "$TARGET_DIR" >>"$DU_TMP" 2>/dev/null; then
partial=true
fi
else
if ! du -h -d 1 -- "$TARGET_DIR" >>"$DU_TMP" 2>/dev/null; then
partial=true
fi
fi
sort -hr "$DU_TMP" | uniq
if [[ "$partial" == true ]]; then
echo "Warning: some entries were skipped (e.g., permission denied)." >&2
fi