-
Notifications
You must be signed in to change notification settings - Fork 0
/
ls-bar
executable file
·77 lines (61 loc) · 2.36 KB
/
ls-bar
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
#!/bin/bash
# Directory to list files (default: current directory)
DIRECTORY="."
SORT=false
# Check for -sort switch
for arg in "$@"; do
case $arg in
-sort)
SORT=true
shift
;;
*)
DIRECTORY="$arg"
shift
;;
esac
done
# Get the file sizes
file_sizes=$(find "$DIRECTORY" -maxdepth 1 -type f -exec stat --format="%s %n" {} \;)
# Check if directory is empty or no files found
if [ -z "$file_sizes" ]; then
echo "No files found in the specified directory."
exit 1
fi
# Sort file sizes if -sort switch is provided
if $SORT; then
file_sizes=$(echo "$file_sizes" | sort -n)
fi
# Get the maximum file size for scaling the bars
max_size=$(echo "$file_sizes" | awk '{print $1}' | sort -n | tail -n 1)
# Find the longest filename
max_filename_length=$(echo "$file_sizes" | awk '{$1=""; print substr($0,2)}' | awk '{print length}' | sort -nr | head -n 1)
# Function to convert bytes to human-readable format
human_readable_size() {
local size=$1
if [ $size -lt 1024 ]; then echo "${size} B"
elif [ $size -lt 1048576 ]; then printf "%.1f K" "$(echo "scale=1; $size/1024" | bc)"
elif [ $size -lt 1073741824 ]; then printf "%.1f M" "$(echo "scale=1; $size/1048576" | bc)"
else printf "%.1f G" "$(echo "scale=1; $size/1073741824" | bc)"
fi
}
# Find the maximum size length for alignment
max_size_length=$(echo "$file_sizes" | awk '{print $1}' | awk '{print length}' | sort -nr | head -n 1)
max_size_length=$((max_size_length + 2)) # Adding space for size unit (B, K, M, G)
# Display the bar graph for each file
echo "File Size Bar Graph:"
echo
# Loop through each file and create a bar graph
while read -r line; do
# Split the size and filename
size=$(echo "$line" | awk '{print $1}')
filename=$(echo "$line" | awk '{$1=""; print substr($0,2)}')
# Calculate the bar length relative to the maximum size
bar_length=$(( (size * 50) / max_size )) # Scale to a max length of 50
# Generate the bar graph using Unicode block characters
bar=$(printf "%-${bar_length}s" "#" | tr ' ' '#')
# Convert size to human-readable format
hr_size=$(human_readable_size $size)
# Display the bar graph with aligned columns
printf "%-${max_filename_length}s %${max_size_length}s | %-50s\n" "$filename" "$hr_size" "$bar"
done <<< "$file_sizes"