Linux: How to Use Tar and Gunzip

Tar is an archival system. It helps bundling many directories and files into a single ‘tarball’. This is convenient for backup and remote transferring purposes. This app is often composed with compression plugins such as Gunzip (normal compression) or tb2 (high) to reduce the overall tarball size. This makes the output even more compact and suitable to be sent over the wire.

Here are a few usual switches:

c : create new archive
x : extract archive
t : list content (not create nor extract)
r : record or append
v : verbosely display progress
p : preserve permissions
f : file name type
z : expect compression
j : high compression often signified with the file suffix .bz2
W : verify archive (doesn't work if gzip or tbz is used)
-C : change extraction direction into a specific path

Some common usage examples:

# Compress the whole /home directory
timeStamp=$(date +"%Y-%m-%d_%H-%M-%S")
tar -czvpf $backupFile $objectToBackup

# Compress the whole /home directory with tb2 high compression
timeStamp=$(date +"%Y-%m-%d_%H-%M-%S")
tar -cvjf $backupFile $objectToBackup

# Extract the compressed archive to the root directory to recreate the original hierarchy
extractTo=/ # WARNING: this will overwrite files in the /home path
tar -xzvf $backupFile -C $extractTo 
tar -xzvf $backupFileBz2 -C $extractTo

# Create an uncompressed archive
timeStamp=$(date +"%Y-%m-%d_%H-%M-%S")
mkdir -p $holdingDirectory && touch -f $usersDatabaseBackup # Create folder and create empty file prior to creating tarball
cd $holdingDirectory && tar -cvf $usersDatabaseBackup passwd

# Add another file into the archive (only works on uncompressed archives)
cd $holdingDirectory && tar -rvf $usersDatabaseBackup {group,shadow,gshadow}

# List contents
tar -tf $usersDatabaseBackup
Posted on Categories Linux

Leave a Reply

Your email address will not be published. Required fields are marked *