absolute.sh 1.47 KB
Newer Older
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
#!/bin/sh
# ---------------------------------------------------------------------------
# Multi-Phasic Applications: SquirrelJME
#     Copyright (C) 2013-2016 Steven Gawroriski <steven@multiphasicapps.net>
#     Copyright (C) 2013-2016 Multi-Phasic Applications <multiphasicapps.net>
# ---------------------------------------------------------------------------
# SquirrelJME is under the GNU Affero General Public License v3, or later.
# For more information see license.txt.
# ---------------------------------------------------------------------------
# DESCRIPTION: Calculates the absolute path of a file

# File to check
__check="$1"

# path is absolute, just needs . and .. removed
if echo "$__check" | grep '^\/' > /dev/null
then
	__yuck="$__check"
	
# Get relative path from PWD
else
	__yuck="$(pwd)/$__check"
fi

# Split path by slashes and handle each line
# Need file due to argument stuff.
rm -f /tmp/$$.abs
touch /tmp/$$.abs
echo "$__yuck" | sed 's/\//\n/g' | while read __seg
do
	# If this segment is ".", ignore it
	# Also ignore blank segments too
	if [ "$__seg" = "." ] || [ -z "$__seg" ]
	then
		continue
	
	# If this is .., remove the topmost path element
	elif [ "$__seg" = ".." ]
	then
		sed 's/\/[^/]*$//g' < /tmp/$$.abs > /tmp/$$.abs2
		mv /tmp/$$.abs2 /tmp/$$.abs
	
	# Otherwise append to path
	else
		echo -n "/$__seg" >> /tmp/$$.abs
	fi
done

# Blank result ends in /
__result="$(cat /tmp/$$.abs)"
rm -f /tmp/$$.abs
if [ -z "$__result" ]
then
	echo "/"
else
	echo "$__result"
fi