Practical Use Cases and Examples
Now that we have learned how to list the contents of zip archives, let us explore some practical scenarios where these skills can be useful. We will work with more realistic examples that you might encounter in daily Linux usage.
Creating a Backup Archive
Creating backups is a common use case for zip archives. Let us create a backup of our configuration files:
cd ~/project/zip_demo
mkdir -p config
echo "server_name=example.com" > config/server.conf
echo "user=admin" > config/user.conf
echo "port=8080" > config/port.conf
## Create a dated backup archive
zip -r backup_$(date +%Y%m%d).zip config/
The command creates a backup file with today's date in the format backup_YYYYMMDD.zip
.
Let us verify the contents of our backup:
unzip -l backup_*.zip
You should see output listing all the configuration files we just backed up.
Comparing Archive Contents
Sometimes you need to compare the contents of two zip archives to see what has changed. Let us create a second backup with some changes:
## Modify a file
echo "port=9090" > config/port.conf
## Add a new file
echo "debug=true" > config/debug.conf
## Create a new backup
zip -r backup_new.zip config/
Now let us compare the contents of the two backup files:
## List files in the first backup
echo "Original backup:"
unzip -l backup_*.zip | grep -v "Archive:" | grep -v "Length" | grep -v "-------"
## List files in the new backup
echo -e "\nNew backup:"
unzip -l backup_new.zip | grep -v "Archive:" | grep -v "Length" | grep -v "-------"
You will notice that the new backup includes the additional debug.conf
file, and the port.conf
file might have a different size due to our modifications.
You can use the information obtained from listing zip contents to extract only specific files:
## Create a directory for extraction
mkdir -p extracted
## List the contents first
unzip -l backup_new.zip
## Extract only the debug.conf file
unzip backup_new.zip "config/debug.conf" -d extracted/
Let us verify that only the requested file was extracted:
ls -la extracted/config/
You should see only the debug.conf
file in the extracted directory.
By mastering these practical examples, you now have the skills to effectively manage zip archives in various real-world scenarios. From creating backups to comparing archive contents and selectively extracting files, these techniques will help you manage your files more efficiently in Linux.