Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash - CD into Untared directory with variable URL

This is the situation. I have a list of URLs that I need to extract and setup. Its all variable driven, but after I extract, I dont know what my folder will be called. I cant CD into it if I dont know what its called.

$DL_DIR = /opt/
$URL = http://nginx.org/download/nginx-1.3.3.tar.gz
$FILE=${URL##*/}
$CONFIG = "-- core"

cd "$DL_DIR"
wget $URL
tar xzf $FILE
cd <HOW DO I GO INTO IT?>
./configure "$CONFIG"
make
make install
rm $FILE

If this doesnt explain it please say. I really want to get past this problem but Im having a hard time explaining it.

Since I want this to function for any set of URL's which may have two formats like ".tar.gz" or one format ".zip" and may have .'s in the filename like "Python2.3.4" or may not "Nginx", it makes it a bit tricky.

like image 330
J.Zil Avatar asked Nov 25 '22 20:11

J.Zil


1 Answers

#! /bin/bash
   #
   # Problem: 
   #  find the path of the "root" folder in an archive
   #
   # Strategy: 
   #  list all folders in the archive.
   #  sort the list to make sure the shortest path is at the top.
   #  print the first line
   # 
   # Weak point:
   #  assumes that tar tf and unzip -l will list files in a certain way
   #  that is: paths ending with / and that the file-list of unzip -l 
   #  is in the fourth column.
   # 

   LIST_FILES=
   FILE=$1
   case ${FILE##*.} in
       gz)
       LIST_FILES="tar tf $FILE"
       ;;
       tgz)
       LIST_FILES="tar tf $FILE"
       ;;
       zip)
       LIST_FILES='unzip -l '$FILE' | awk "{print \$4}"'
       ;;
   esac
   ARCHIVE_ROOT=$(
   echo $LIST_FILES | sh |\
       grep '/$'|\
       sort |\
       head -n1
   )

   # we should have what we need by now, go ahead and extract the files.
   if [ -d "$ARCHIVE_ROOT" ]; then
       cd "$ARCHIVE_ROOT"
   else
       # there is no path (whoever made the archive is a jerk)
       # ...or the script failed (see weak points)
       exit 1
   fi
like image 163
Ярослав Рахматуллин Avatar answered Nov 29 '22 04:11

Ярослав Рахматуллин