89
votes

I'm working on a backup script and want to tar up a file directory:

tar czf ~/backup.tgz /home/username/drupal/sites/default/files

This tars it up, but when I untar the resulting file, it includes the full file structure: the files are in home/username/drupal/sites/default/files.

Is there a way to exclude the parent directories, so that the resulting tar just knows about the last directory (files)?

9

9 Answers

41
votes
cd /home/username/drupal/sites/default/files
tar czf ~/backup.tgz *
175
votes

Use the --directory option:

 tar czf ~/backup.tgz --directory=/home/username/drupal/sites/default files 
55
votes

Hi I've a better solution when enter in the specified directory it's impossible (Makefiles,etc)

tar -cjvf files.tar.bz2 -C directory/contents/to/be/compressed .

Do not forget the dot (.) at the end !!

5
votes

Create a tar archive

tar czf  $sourcedir/$backup_dir.tar --directory=$sourcedir WEB-INF en

Un-tar files on a local machine

tar -xvf $deploydir/med365/$backup_dir.tar -C $deploydir/med365/

Upload to a server

scp -r -i $privatekey $sourcedir/$backup_dir.tar $server:$deploydir/med365/
echo "File uploaded.. deployment folders"

Un-tar on server

ssh -i $privatekey $server tar -xvf $deploydir/med365/$backup_dir.tar -C $deploydir/med365/
2
votes

To gunzip all txt (*.txt) files from /home/myuser/workspace/zip_from/ to /home/myuser/workspace/zip_to/ without directory structure of source files use following command:

tar -P -cvzf /home/myuser/workspace/zip_to/mydoc.tar.gz  --directory="/home/myuser/workspace/zip_from/" *.txt
0
votes

This worked for me:

gzip -dc "<your_file>.tgz" | tar x -C <location>
0
votes

For me -C or --directory did not work, I use this

cd source/directory/or/file
tar -cvzf destination/packaged-app.tgz *.jar
# this will put your current directory to what it previously was
cd -
0
votes

Kindly use the below command to generate tar file without directory structure

tar -C <directoryPath> -cvzf <Path of the tar.gz file> filename1 filename2... filename N

eg:

tar -C /home/project/files -cvzf /home/project/files/test.tar.gz text1.txt text2.txt
-3
votes
tar -Cczf ~/backup.tgz /home/username/drupal/sites/default/files

-C does the cd for you