-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextract
66 lines (63 loc) · 1.59 KB
/
extract
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
#!/bin/sh
# Extract the archive $1 to a directory $2 with the program $3. If the
# archive contains a single top-level directory, that directory
# becomes $2. Otherwise $2 contains all the files at the root of the
# archive.
extract () (
set -e
archive=$1
case "$archive" in
-) :;; # read from stdin
/*) :;; # already an absolute path
*) archive=$PWD/$archive;; # make absolute path
esac
target=$2
program=$3
if [ -e "$target" ]; then
echo >&2 "Target $target already exists, aborting."
return 3
fi
case "$target" in
/*) parent=${target%/*};;
*/[!/]*) parent=$PWD/${target%/*};;
*) parent=$PWD;;
esac
temp=$(TMPDIR="$parent" mktemp -d)
(cd "$temp" && $program "$archive")
root=
for member in "$temp/"* "$temp/".*; do
case "$member" in */.|*/..) continue;; esac
if [ -n "$root" ] || ! [ -d "$member" ]; then
root=$temp # There are multiple files or there is a non-directory
break
fi
root="$member"
done
if [ -z "$root" ]; then
# Empty archive
root=$temp
fi
mv -v -- "$root" "$target"
if [ "$root" != "$temp" ]; then
rmdir "$temp"
fi
)
# Extract the archive $1.
process () {
dir=${1%.*}
case "$1" in
*.rar|*.RAR) program="unrar x";;
*.tar|*.tgz|*.tbz2) program="tar -xf";;
*.tar.gz|*.tar.bz2|*.tar.xz) program="tar -xf"; dir=${dir%.*};;
*.zip|*.ZIP) program="unzip";;
*) echo >&2 "$0: $1: unsupported archive type"; exit 4;;
esac
if [ -d "$dir" ]; then
echo >&2 "$0: $dir: directory already exists"
exit 1
fi
extract "$1" "$dir" "$program"
}
for x in "$@"; do
process "$x"
done