aboutsummaryrefslogtreecommitdiff
path: root/snag/scripts/extract_tar_contents.sh
blob: a50a1a73df729b09e83a8e98c433388cf85fc30b (plain)
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
#!/bin/sh
set -e

# extracts a tarball's contents to the output directory.
# if the tarball contains just one directory, extract those contents
#
# we can rewrite this script in c eventually, if we want

if [ -z "$1" -o -z "$2" ]; then
    echo "Usage: $0 <tarball> <output_directory>" >&2
    exit 1
fi

tarball="$1"
target="$2"

is_one_directory() {
	if [ $(echo $1 | wc -l) -ne 1 ]; then
		return 1
	fi
	case "$1" in
		*/) return 0 ;;
		*)  return 1 ;;
	esac
}

# get top level paths in tarball
tlps=$(tar -tf "$tarball" | grep -E '^(./)?[^/]+/?$')

if is_one_directory "$tlps"; then
	# if only one top level directory, extract it and rename it
	tar xf "$tarball"
	mv "$tlps" "$target"
else
	# if a bunch of files or directories, extract them in a directory
	mkdir $target
	tar xf "$tarball" -C "$target"
fi