Imported from ../bash-2.0.tar.gz.
[platform/upstream/bash.git] / examples / scripts.v2 / untar
1 #! /bin/bash
2 #
3 # original from:
4 # @(#) untar.ksh 1.0 93/11/10
5 # 92/10/08 john h. dubois iii (john@armory.com)
6 # 92/10/31 make it actually work if archive isn't in current dir!
7 # 93/11/10 Added pack and gzip archive support
8 #
9 # conversion to bash v2 syntax done by Chet Ramey
10
11 phelp()
12 {
13 echo \
14 "$name: extract tar archives into directories, uncompressing if neccessary.
15 Usage: $name archive[.tar[.[Z|gz]]] ..
16 If an archive name given does not end in .tar, .tar.Z, or .tar.gz, it is
17 searched for first with .tar added, then .tar.Z, and then .tar.gz added. 
18 The real filename must end in either .tar, .tar.Z, or .tar.gz.  A
19 directory with the name of the archive is created in the current directory
20 (not necessarily the directory that the archive is in) if it does not
21 exist, and the the contents of the archive are extracted into it. 
22 Absolute pathnames in tarfiles are suppressed."
23 }
24
25 if [ $# -eq 0 ]; then
26     phelp
27     exit 1
28 fi
29
30 name=${0##/}
31 OWD=$PWD
32
33 for file; do
34     cd $OWD
35     case "$file" in
36     *.tar.Z)    ArchiveName=${file%%.tar.Z} zcat=zcat;;
37     *.tar.z)    ArchiveName=${file%%.tar.z} zcat=pcat;;
38     *.tar.gz)   ArchiveName=${file%%.tar.gz} zcat=gzcat;;
39     *)  ArchiveName=$file
40         for ext in "" .Z .z .gz; do
41             if [ -f "$file.tar$ext" ]; then
42                 file="$file.tar$ext"
43                 break
44             fi
45         done
46         if [ ! -f "$file" ]; then
47             echo "$file: cannot find archive." 1>&2
48             continue
49         fi
50         ;;
51     esac
52     if [ ! -r "$file" ]; then
53         echo "$file: cannot read." >&2
54         continue
55     fi
56     DirName=${ArchiveName##*/}
57     [ -d "$DirName" ] || {
58         mkdir "$DirName" || {
59                 echo "$DirName: could not make archive directory." 1>&2
60                 continue
61         }
62     }
63
64     cd $DirName || {
65         echo "$name: cannot cd to $DirName" 1>&2
66         continue
67     }
68
69     case "$file" in
70     /*) ;;
71     *) file=$OWD/$file ;;
72     esac
73
74     echo "Extracting archive $file into directory $DirName..."
75     case "$file" in
76     *.tar.Z|*.tar.z|*.tar.gz) $zcat $file | tar xvf -;;
77     *.tar) tar xvf $file;;
78     esac
79     echo "Done extracting archive $file into directory $DirName."
80 done