Shell: Tar files: programmatically determining the name of the target directory
Hey Gang,
As part of a larger project, I'm looking for a way to automatically do the following with a ton of different tar.gz files: 1. Determine the target directory of a .tar.gz file 2. Remove the directory, if it exists 3. Untar the new .tar file into the target directory again Anyone have a good way to determine the target directory of a .tar.gz file? This might seem easy, but it's complicated by the fact that the target directory and the .tar.gz file often have inconsistant names. The tar file might expand into the CWD '.', or. In Debian, the .tar.gz is named apache2_2.0.54.orig.tar.gz and the directory is named "apache2-2.0.54"-- with a dash instead of an underscore. Here is my first attempt: Code:
#!/bin/bash -x |
Have you considered something like:
Code:
TAR_DIR=`tar zft $TAR_FILE | head -n1` |
Hi.
If the first part of the path is the same for _every_ file in the tar.gz, then you know that will be the directrory which will be created when it is untarred. In any other case, the tar file will unpack to '.'. You could test for this with: Code:
TARGETDIRNUM=`tar tzf abcdefg.tar.gz | cut -f1 -d/ | uniq | wc | awk '{print $1}'` Assuming there is a target directory, you can get its name from the code in post #2, with a 'cut' command. Dave P.S. Watch what you're doing with paths that start with / , and don't be root, for obvious reasons. |
Thanks ilikejam, that's a good check.
I have a longer version of the code here, where I deal with special exceptions like '.' . Great pointer regarding paths that being with '/' though. This is getting so hairy ... Here's a slightly modified version of your solution. I removed the awk part, since awk can be problematic on some systems. Code:
TARGETDIRNUM=`tar jtf $TAR_FILE | cut -f1 -d/ | uniq |wc -l` |
All times are GMT -5. The time now is 09:23 PM. |