How to use tar command?
tar (tape archive) command bundles a bunch of files together and creates an archive (commonly called a tar file or tarball) on a tape, disk drive, or floppy disk. The original files are not deleted after being copied to the tar file. To create an archive using tar, use a command like this, which bundles all the files in the current directory that end with .jpg into the alldocs.tar file:
tar -cvf alldocs.tar *.jpg
- The below command tars all contents of “abcd” folder, into “abcd.tar”.
tar -cvf panda.tar abcd/
Below options are used throughout in all different commands .
t – List the contents of an archive.
x – Extract the contents of an archive.
f – The archive file name is given on the command line (required whenever the tar output is going to a file)
M- The archive can span multiple floppies.
v – Print verbose output (list file names as they are processed).
u – Add files to the archive if they are newer than the copy in the tar file.
z – Compress or decompress files automatically.
- Command to create tar files on tape drives or floppy disks, like this:
tar -cvfM /dev/fd0
- To automatically compress the tar file as it is being created, add the z flag, like this:
.gz suffix to the archive file name, as z flag tells tar to use the same compression as the gzipcommand.
- Command to list all files in alldocs.tar.
- To extract the contents of a tar file, use the x (extract) flag in a command, like this:
tar -xvf abcd.tar
Extract files from abcd.tar
- Creating a bzipped tar archive using option cvjf
Note: .tbz and .tb2 is same as .tar.bz2
Extract a gzipped tar archive ( *.tar.gz ) using option xvzf
tar -xvzf archive_name.tar.gz
tar -xvjf archive_name.tar.bz2
- Extract a single file from tar, tar.gz, tar.bz2 file
tar xvf archive_file.tar /path/to/file
Use the relevant option z or j according to the compression method gzip or bzip2 respectively as shown below.
- Extract a single directory from tar, tar.gz, tar.bz2 file
The following extracts only a specific directory from a large tar file.
- Extract multiple directories from a tar archive, specify those individual directory names at the end of the tar xvf command as shown below.
- Adding a file or directory to an existing archive using option -r
tar -rvf archive_name.tar newfile
- Adding a directory to the tar is also similar,
- Verify files available in tar using option -W
- Estimate the tar archive size ( in KB )
tar -cf – /directory/to/archive/ | wc -c