How to Create a Tar File to a Specific Folder from a Different Folder

Hi guys i am new to linux.

I am trying to create a tar file from a different directory and want to be placed a specific directory.

I have tried this cmd

tar -cvf dailybackup.tar /root/filesfromlocalmachine/ -C /root/backup/

There is a folder in the name pf backup and i want the tar to be created there. But whenever i execute this the tar is been created at the folder where i am executing the command. Is there a way to create a tar file from a different folder.

0

2 Answers

Yes, put the directory in front of the "tar".

cd /
tar -cvf /where/to/put/it/dailybackup.tar root/backup/

and it will backup root/backup.

I would suggest to always makes backups with a relative path (as I used in my answer) otherwise you might overwrite the destination when you wanted to restore it elsewhere and then do a compare with the backup version.

2

Whenever tar encounters a -C option, the current working directory changes, all subsequent options that follow are affected. It makes this option order-sensitive.

./a:      ./b:
file001   file002

e.g., using multiple -C options makes the second -C relative to the first.

$ tar -vcf archive.tar.gz -C ./a . -C ../b .  
./  
./file001  
./  
./file002

Because -C does not adjust the [FILE...] entry, path expansion (... globbing) will not work. However, in cases where globbing is required, --transform may be used.

$ tar -cvf archive.tar.gz \
    --show-transformed-names --transform='s:^./.*/::' ./[ab]/file00?
file001
file002

also, '--strip-components=<n>' can be used to strip leading components on extraction.

$ tar -vxf archive.tar.gz \
    --show-transformed-names --strip-components=2  
file001  
file002

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest