-
Notifications
You must be signed in to change notification settings - Fork 0
/
maxsize.sh
94 lines (80 loc) · 2.63 KB
/
maxsize.sh
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#!/bin/bash
# A script to calculate the largest files and directories in a specified directory
# Usage: ./maxsize.sh [-n number] [directory]
# Default number of items to display
count=10
# Parse command-line options
while getopts ':n:' OPTION; do
# Handle arguments that require a value
case "$OPTION" in # $OPTARG is the value that is passed to the option
n)
# Check if the value is an integer
if [[ "$OPTARG" =~ ^[0-9]+$ ]]; then
# Set the count to the provided value
count="$OPTARG"
else
# Print an error message if the value is not an integer
echo "Error: -n option requires an integer." >&2
exit 1
fi
;;
?)
# Print usage information if an invalid option is provided
echo "Usage: $(basename "$0") [-n number] [directory]" >&2
exit 1
;;
esac
done
# Remove the options from the positional parameters
shift "$((OPTIND -1))"
# Use the current directory if none is provided
directory="${1:-.}"
# Check if the specified directory exists
if [[ ! -d "$directory" ]]; then
# Print an error message and exit if the directory does not exist
echo "The specified directory does not exist: $directory" >&2
exit 1
fi
# Display the number of items to show
echo "Scanning $directory for the largest $count files and directories by size..."
# Function to display a spinner while the script is running
spin(){
spinner="/|\\-/|\\-"
while :
do
for i in $(seq 0 7)
do
echo -ne "${spinner:$i:1}"
echo -ne "\010"
sleep 0.2
done
done
}
# Run the spinner function in the background
spin &
SPIN_PID=$!
disown
# Find and sort the largest files
echo "Largest files:"
find "$directory" -type f -exec du -h {} + | sort -rh | head -n "$count"
# Calculate and display the total size of files directly in each directory (non-recursive)
echo "Directories with the most file size (non-recursive):"
# Loop through each subdirectory
while IFS= read -r dir; do
# Calculate the total size of files in the directory
total_size=$(find "$dir" -maxdepth 1 -type f -exec du -k {} + | awk '{sum += $1} END {print sum}')
# Set total_size to 0 if it is not set
total_size=${total_size:-0} # Default to 0 if not set
# Display the directory and total size if it is greater than 0
if [ "$total_size" -gt 0 ]; then
echo "$dir contains $total_size KB"
fi
# Pass the list of directories to the while loop
done < <(find "$directory" -type d) | sort -k3 -nr | head -n "$count"
# Kill the spinner process
kill $SPIN_PID
wait $SPIN_PID 2>/dev/null
# Indicate that the operation is complete
echo "Operation completed."
# Exit with a successful status
exit 0