-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpart2.sh
executable file
·61 lines (50 loc) · 1.42 KB
/
part2.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
#!/bin/bash
# space available = 70G
# req free space = 30G
# used space = $dir[/]
# unused space (u) = 70G - $dir[/]
# minimum space to be deleted = 30G - (u)
file="./input.txt";
total=0;
currentDir="";
declare -A dirs;
# get all directories total sizes
while read -r line; do
if [ "$line" == "$ cd /" ]; then
currentDir="/";
elif [[ "$currentDir" != "/" && "$line" == "$ cd .." ]]; then
currentDir="${currentDir%*/*/}/";
elif [[ "$line" =~ ^\$\ cd ]]; then
currentDir+="${line:5}/";
elif [[ "$line" =~ ^\$\ ls ]]; then
dirs[$currentDir]=0;
elif [[ "$line" =~ ^dir ]]; then
# dir
# can be ignored
continue;
else
# file
# add size to directorys total size
((dirs[$currentDir]+=${line% *}));
fi
done < $file;
# sort paths (keys of $dirs)
paths=($(for path in "${!dirs[@]}"; do echo "$path"; done | sort -r));
# correct dir sizes
for path in "${paths[@]}"; do
dirSize=${dirs[$path]};
parent="${path%*/*/}/";
((dirs[$parent]+=dirSize));
done
# calculate minimum space to be deleted
minSize=$((70000000 - ${dirs[/]})); # unused space
minSize=$((30000000 - minSize)); # min space
# get smallest dir which could be deleted
smallestSize=${dirs[/]};
for path in "${paths[@]}"; do
dirSize=${dirs[$path]};
if [[ $dirSize -ge $minSize && $dirSize -lt $smallestSize ]]; then
smallestSize=$dirSize;
fi
done
echo "Answer: $smallestSize";