3

I am fairly new using tar having used zip files in the past.

I want to just create the tar file without the directories being included.

I went here, but found it a bit confusing.

https://www.baeldung.com/linux/tar-archive-without-directory-structure

# Backup crontab
crontab -l > /home/andy/bin/crontab_backup.txt
tar -cvf /home/andy/bin/crontab_backup.tar /home/andy/bin/crontab_backup.txt
fixit7
  • 3,399

3 Answers3

8

For your specific example, if you cd to the /home/andy/bin and omit that path in the commands, you'll get the desired result:

# Backup crontab
cd /home/andy/bin
crontab -l > crontab_backup.txt
tar -cvf crontab_backup.tar crontab_backup.txt

This is the suggestion in 3.2 Using the tar Command in the Target Directory in the page you linked to and is probably the simplest way for this particular problem.

The equivalent of 3.1. Using the -C Option for a Single Directory would be:

crontab -l > /home/andy/bin/crontab_backup.txt
tar -cvf /home/andy/bin/crontab_backup.tar -C /home/andy/bin crontab_backup.txt

There is another option that's not mentioned in the linked page: --transform, which allows us to use a s/<pattern>/<replacement>/ expression like in sed.

crontab -l > /home/andy/bin/crontab_backup.txt
tar -cvf /home/andy/bin/crontab_backup.tar /home/andy/bin/crontab_backup.txt --transform 's,.*/,,'
muru
  • 207,228
6

With GNU tar you can use the -C option to change directory partway through the command. Filenames are still recorded relative to the current directory, so it means so you can do this:

tar -cvf /home/andy/bin/crontab_backup.tar -C /home/andy/bin crontab_backup.txt

and if you wanted to collect two files from different directories, you could do this:

tar -cvf /home/andy/bin/crontab_backup.tar -C /home/andy/bin crontab_backup.txt -C /home/andy other_file.txt
2

The tar command really does not have options to not store the directory structure, in line with the linux philosophy of "do one thing and do it well".

The page you refer to provides some trick to store files without the directory structure. However, these trick are very limited in their power, and require you to specify each lowest level directory that contains files. The trick will already fail if there also are files in directories in the middle of the tree. Tarring these will include the lower directories.

As such, it is not possible in a fully automated way. A more automated way would require preparing a directory containing all files from the directory tree at the top level directory first, then tar that directory. On a file system that supports linux permissions, that could be done using hard links, so no extra space is needed for the temporary copy.

You could do so with find:

find /path/to/parent/dir -type f -exec ln {} /path/to/new/dir \;

then you can tar the directory dir in /path/to/new.

vanadium
  • 97,564