-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathextract
108 lines (90 loc) · 3.52 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#!/bin/bash
# @author Samuel Walters-Nevet #
# @date Summer, 2016; updated Spring 2017 #
# @brief Extracts an archive based upon its file extension #
# @file extract.sh #
# #
# Prerequisits: #
# sudo apt install tar xz-utils bzip2 unrar gzip unzip p7zip cabextract #
# #
# Note: #
# Aliasing this script in your bashrc file ('~/.bashrc') can make this a lot more useful: #
alias extract='bash ~/scripts/extract.sh'
#############################################################################################################
autoincr() {
f="$1"
ext=""
[[ "$f" == *.* ]] && ext=".${f##*.}"
if [[ -e "$f" ]] ; then
i=1
f="${f%.*}";
while [[ -e "${f}_${i}${ext}" ]]; do
let i++
done
f="${f}_${i}${ext}"
fi
echo "$f"
}
function extract {
for f in "$@"; do
if [[ -z "$f" ]]; then
# display usage if no parameters given
echo "Usage: extract <archive>"
exit 1;
elif [[ -z "$f" ]]; then
# display usage if no parameters given
echo "$f - file does not exist"
exit 2;
fi
FILE="$(realpath "$f")"
DIR="${FILE%.*}"
if [[ "$DIR" == *.part[[:digit:]]* ]]; then
PART="${DIR##*.part}"
PART="${PART%.*}"
if [ "$PART" -eq "$PART" ] 2>/dev/null; then
DIR="${DIR%.part*}"
fi
fi
while [[ -e "$DIR" ]]; do
DIR="$(autoincr "$DIR")"
done
CUR_DIR="$PWD"
DIR_TEMP="${DIR}.temp"
mkdir "$DIR_TEMP" && cd "$DIR_TEMP"
case "$FILE" in
*.tar.bz2) tar xvjf "$FILE" ;;
*.tar.gz) tar xvzf "$FILE" ;;
*.tar.xz) tar xvJf "$FILE" ;;
*.lzma) unlzma "$FILE" ;;
*.bz2) bunzip2 "$FILE" ;;
*.rar) unrar x -ad "$FILE" ;;
*.gz) gunzip "$FILE" ;;
*.tar) tar xvf "$FILE" ;;
*.tbz2) tar xvjf "$FILE" ;;
*.tgz) tar xvzf "$FILE" ;;
*.zip) unzip "$FILE" ;;
*.Z) uncompress "$FILE" ;;
*.7z) 7z x "$FILE" ;;
*.xz) unxz "$FILE" ;;
*.exe) cabextract "$FILE" ;;
*) echo "extract: '$FILE' - unknown archive method" ;;
esac
cd "$CUR_DIR"
# @TODO:
# Add method such that:
# If there is only 1 sub-directory:
# contents are moved tor DIR_TEMP, and *then* anylized
if [[ "$(ls -l "$DIR_TEMP" | wc -l)" == 2 ]]; then
SUB_DIR="${DIR_TEMP}/$(ls "$DIR_TEMP")";
if [[ -f "$SUB_DIR" ]]; then
mv "$SUB_DIR" "${DIR}.${SUB_DIR##*.}"
else
mv "$SUB_DIR" "$DIR"
fi
rmdir "$DIR_TEMP"
else
mv "$DIR_TEMP" "$DIR"
fi
done
}
extract "$@"