-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path.shorten-path.bash
73 lines (68 loc) · 1.55 KB
/
.shorten-path.bash
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
# Simple BASH function that shortens
# a very long path for display by removing
# the left most parts and replacing them
# with a leading ...
#
# the first argument is the path
#
# the second argument is the maximum allowed
# length including the '/'s and ...
#
shorten_path()
{
x=${1}
len=${#x}
max_len=$2
if [ $len -gt $max_len ]
then
# finds all the '/' in
# the path and stores their
# positions
#
pos=()
for ((i=0;i<len;i++))
do
if [ "${x:i:1}" == "/" ]
then
pos=(${pos[@]} $i)
fi
done
pos=(${pos[@]} $len)
# we have the '/'s, let's find the
# left-most that doesn't break the
# length limit
#
i=0
while [ $((len-pos[i])) -gt $((max_len-3)) ]
do
i=$((i+1))
done
# let us check if it's OK to
# print the whole thing
#
if [ ${pos[i]} == 0 ]
then
# the path is shorter than
# the maximum allowed length,
# so no need for ...
#
echo ${x}
elif [ ${pos[i]} == $len ]
then
# constraints are broken because
# the maximum allowed size is smaller
# than the last part of the path, plus
# '...'
#
echo ...${x:((len-max_len+3))}
else
# constraints are satisfied, at least
# some parts of the path, plus ..., are
# shorter than the maximum allowed size
#
echo ...${x:pos[i]}
fi
else
echo ${x}
fi
}