Let's say the /tmp/example directory contains two files, foo.txt and bar.txt, like this. Notice each file has a unique owner and permissions.
~]# ls -l /tmp/sample
-rw-r--r-- 1 jane.doe admins 0 Oct 20 03:19 foo.txt
-rwxrwxrwx 1 john.doe admins 0 Oct 20 03:19 bar.txt
The tar command with the -c or --create and -f or --file optiions can be used to create a tar archive of a directory, like this. tar is recursive, meaning that all files and folders below the target directory will be included in the archive.
tar -cf example.tar /tmp/sample
The -v or --verbose option can be used to display the files being added to the archive.
tar -cvf example.tar /tmp/sample
. . .
/tmp/sample/
/tmp/sample/bar.txt
/tmp/sample/foo.txt
The tar command with the -t or --list and -f or --file optiions can be used to view the contents of the tar achive.
tar -tf example.tar
Which will produce the following.
tmp/sample/
tmp/sample/bar.txt
tmp/sample/foo.txt
Present Working Directory
The tar command does take into consideration your present working directory. Notice in this example that tmp/ is not included in the tar archive, since we are in the /tmp directory.
cd /tmp
tar -cvf example.tar sample
. . .
sample/
sample/foo.txt
sample/bar.txt
Compression (gzip, bzip, pigz)
Adding the -z or --use-compress-program=gzip option and the tar.gz or .tgz extension will create a gzip compressed archive.
tar -zcf example.tar.gz /tmp/sample
tar -zcf example.tgz /tmp/sample
When the archive is gzip compressed, the -z option will need to be used to view the contents of the archive, like this:
tar -ztf example.tar.gz
Adding the -j or --use-compress-program=bzip option and .bz2 extension will create a bzip2 compressed archive.
tar -jcf example.tar.bz2 /tmp/sample
When the archive is gzip compressed, the -z option will need to be used to view the contents of the archive, like this:
tar -jtf example.tar.gz
Or, pigz could be used.
tar --use-compress-program=pigz -cf example.tar.pigz /tmp/sample
In this example, the uncompressed archive is 16179200 bytes, the gzip compressed archive is 3466105 bytes, and the bzip2 compressed archive is 289751 bytes.
ls -l
. . .
-rw-rw-r--. 1 john.doe john.doe 16179200 May 8 12:53 example.tar
-rw-rw-r--. 1 john.doe john.doe 3466105 May 8 12:55 example.tar.gz
-rw-rw-r--. 1 john.doe john.doe 2897541 May 8 12:58 example.tar.bz2
Excluding directories
The --exclude option can be used to exclude directories. In this example, /tmp/sample/foo will be excluded.
tar -cf example.tar --exclude="/tmp/sample/foo" /tmp/sample