You can use a combination of tar options to achieve this: tar option to list:
-t,
tar option to extract to another directory:
-C,
So, in the script you can list the files and check if there are any files in the list that do not have a "/", and based on this output, you can call tar with the appropriate parameters.
A sample for your reference is as follows:
TAR_FILE=<some_tar_file_to_be_extracted>
In some cases, the tar file may contain different directories. If you find it a little annoying to look for different directories that are extracted by the same tar file, then the script can be modified to create a new directory, even if the list contains different directories. A slightly advanced sample is as follows:
TAR_FILE=<some_tar_file_to_be_extracted> # List the files in the .tgz file using tar -tf # Look for only directory names using cut, # Current cut option used lists each files as different entry # Count the number unique directories, if the count is > 1, create directory if [ `tar -tf ${TAR_FILE} |cut -d '/' -f 1|uniq|wc -l` -gt 1 ];then echo "Found file(s) which is(are) not in same directory" # Directory name will be the tar file name excluding everything after last "." # Thus "test.a.sh.tgz" will give a directory name "test.a.sh" DIR_NAME=${TAR_FILE%.*} echo "Extracting in ${DIR_NAME}" # Test if the directory exists, if not then create it # If directory exists prompt user to enter directory to extract to # It can be a new or existing directory if [ -d ${DIR_NAME} ];then echo "${DIR_NAME} exists. Enter (new/existing) directory to extract to" read NEW_DIR_NAME # Test if the user entered directory exists, if not then create it [ -d ${NEW_DIR_NAME} ] || mkdir ${NEW_DIR_NAME} else mkdir ${DIR_NAME} fi # Extract to the directory instead of cwd tar xzvf ${TAR_FILE} -C ${DIR_NAME} else # Extract to cwd tar xzvf ${TAR_FILE} fi
Hope this helps!
source share