What I wanted to do
I wanted to archive files on a server for backup and compress logs to save disk space. Both tar and zip come up all the time, but I kept looking up the options every single time.
Basic tar commands
Create an archive (no compression)
tar -cvf archive.tar ./mydir
-c: create-v: verbose output-f: specify the filename
Create with gzip compression (.tar.gz)
tar -czvf archive.tar.gz ./mydir
Create with bzip2 compression (.tar.bz2)
tar -cjvf archive.tar.bz2 ./mydir
Extracting with tar
# Extract a .tar file
tar -xvf archive.tar
# Extract a .tar.gz file
tar -xzvf archive.tar.gz
# Extract a .tar.bz2 file
tar -xjvf archive.tar.bz2
# Extract to a specific directory
tar -xzvf archive.tar.gz -C /tmp/
List archive contents without extracting
tar -tzvf archive.tar.gz
Basic zip commands
# Compress files
zip archive.zip file1.txt file2.txt
# Compress a directory recursively
zip -r archive.zip ./mydir
# Set compression level (0-9, default is 6)
zip -r -9 archive.zip ./mydir
Extracting with unzip
# Extract to current directory
unzip archive.zip
# Extract to a specific directory
unzip archive.zip -d /tmp/output
# List contents without extracting
unzip -l archive.zip
Common patterns
Archive logs with a date stamp
tar -czvf "logs-$(date +%Y%m%d).tar.gz" /var/log/nginx/
Exclude specific files or directories
tar -czvf archive.tar.gz ./mydir --exclude='*.log' --exclude='node_modules'
Check compression ratio
ls -lh archive.tar.gz
du -sh ./mydir
Gotchas
- The
-fflag intarmust come last in the option string — the filename immediately follows-f - Forgetting
-rinzip -rmeans the directory contents won’t be included .tar.gzand.tgzare the same format, so either extension works fine with the same optionsunzipmay not be installed on a fresh Linux server — install it withapt install unzip- Using absolute paths with
tarcan cause files to extract to unexpected locations; be aware of leading/in paths
Related articles
- Linux Basic Commands (ls/cd/mkdir/rm)
- How to Sync and Backup Files with rsync
- Linux SSH Basics: How to Connect to a VPS
- How to Fix Permission Denied Error on Linux
Recommended Cloud Hosting
Looking for reliable cloud infrastructure? Check out these developer-friendly services.
- Cherry Servers - High-performance VPS and dedicated servers
- Cloudways - Managed cloud hosting for developers