How to Unzip Files in Linux
Updated Feb 25, 2020
ZIP is the most widely used archive file format that supports lossless data compression. A ZIP file is a data container containing one or more compressed files or directories.
In this tutorial, we will explain how to unzip files in Linux systems through the command line using the unzip command.
Installing unzip #
unzip is not installed by default in most Linux distributions, but you can easily install it using the package manager of your distribution.
Install unzip on Ubuntu and Debian #
Install unzip on CentOS and Fedora #
How to Unzip a ZIP file #
In it’s simplest form, when used without any option, the unzip command extracts all files from the specified ZIP archive to the current directory.
As an example, let’s say you downloaded the WordPress installation ZIP file. To unzip this file to the current directory, you’d simply run the following command:
ZIP files do not support Linux-style ownership information. The extracted files are owned by the user that runs the command.
You must have write permissions on the directory where you are extracting thr ZIP archive.
Suppress the Output of the unzip Command #
By default, unzip prints the names of all the files it’s extracting and a summary when the extraction is completed.
Use the -q switch to suppress the printing of these messages.
Unzip a ZIP File to a Different Directory #
To unzip a ZIP file to a different directory than the current one, use the -d switch:
For example, to unzip the WordPress archive latest.zip to the /var/www/ directory, you’d use the following command:
In the command above, we are using sudo because usually the user we are logged in as doesn’t have write permissions to the /var/www directory. When ZIP files are decompressed using sudo , the extracted files and directories are owned by the user root.
Unzip a Password Protected ZIP file #
To unzip a file that is password-protected, invoke the unzip command with the -P option followed by the password:
Typing a password on the command line is insecure and should be avoided. A more secure option is to extract the file normally without providing the password. If the ZIP file is encrypted, unzip will prompt you to enter the password:
unzip will use the same password for all encripted files as long as it is correct.
Exclude Files when Unzipping a ZIP File #
To exclude specific files or directories from being extracted, use the -x option followed by space-separated list of archive files you want to exclude from extracting:
In the following example we are extracting all files and directories from the ZIP archive except the .git directory:
Overwrite Existing Files #
Let’s say you’ve already unzipped a ZIP file and you are running the same command again:
By default, unzip will ask you whether you like to overwrite only the current file, overwrite all files, skip extraction of the current file, skip extraction of all files, or rename the current file.
If you want to overwrite existing files without prompting, use the -o option:
Use this option with caution. If you made any changes to the files, the changes are lost.
Unzip a ZIP File Without Overwriting Existing Files #
Let’s say you’ve already unzipped a ZIP file, and you made changes to some files, but you accidentally deleted few files. You want to keep the changes and to restore the deleted files from the ZIP archive.
In this case, use the -n option which forces unzip to skip the extraction of a file that already exists:
Unzip Multiple ZIP Files #
You can use regular expressions to match multiple archives.
For example, if you have multiple ZIP files in your current working directory you can unzip all files using only one command:
Note the single quotes around the *.zip . If you forgot to quote the argument, the shell will expand the wildcard character, and you will get an error.
List the Contents of a Zip File #
To list the contents of a ZIP file, use the -l option:
In the example below, we are listing all WordPress installation files:
The output will look like this:
Conclusion #
unzip is a utility that helps you list, test, and extract compressed ZIP archives.
To create a ZIP archive on a Linux system, you’ll need to use the zip command .
Feel free to leave a comment if you have any questions.
How to Unzip a Zip File in Linux [Beginner’s Tutorial]
Last updated October 9, 2019 By Abhishek Prakash 9 Comments
Brief: This quick tip shows you how to unzip a file in Ubuntu and other Linux distributions. Both terminal and GUI methods have been discussed.
Zip is one of the most common and most popular way to create compressed archive files. It is also one of the older archive file format that was created in 1989. Since it is widely used, you’ll regularly come across a zip file.
In an earlier tutorial, I showed how to zip a folder in Linux. In this quick tutorial for beginner’s, I’ll show you how to unzip files in Linux.
Prerequisite: Verify if you have unzip installed
In order to unzip a zip archive file, you must have the unzip package installed in your system. Most modern Linux distributions come with uzip support but there is no harm in verifying it to avoid bad surprises later.
In Ubuntu and Debian based distributions, you can use the command below to install unzip. If it’s already installed, you’ll be notified about it.
Once you have made sure that your system has unzip support, it’s time to unzip a zip file in Linux.
You can use both command line and GUI for this purpose and I’ll show you both methods.
Unzip file in Linux command line
Using unzip command in Linux is absolutely simple. In the directory, where you have the zip file, use this command:
You can also provide the path to the zip file instead of going to the directory. You’ll see extracted files in the output:
There is a slight problem with the above command. It will extract all the contents of the zip file in the current directory. That’s not a pretty thing to do because you’ll have a handful of files leaving the current directory unorganized.
Unzip to directory
A good practice is to unzip to directory in Linux command line. This way, all the extracted files are stored in the directory you specified. If the directory doesn’t exist, it will create one.
Now all the contents of the zipped_file.zip will be extracted to unzipped_directory.
Since we are discussing good practices, another tip you can use is to have a look at the content of the zip file without actually extracting it.
See the content of zip file without unzipping it
You can check the content of the zip file without even extracting it with the option -l.
Here’s a sample output:
There are many other usage of the unzip command in Linux but I guess now you have enough knowledge to unzip files in Linux.
Unzip files in Linux using GUI
You don’t always have to go to the terminal if you are using desktop Linux. Let’s see how to unzip in Ubuntu Linux graphically. I am using GNOME desktop here with Ubuntu 18.04 but the process is pretty much the same in other desktop Linux distributions.
Open the file manager and go to the folder where your zip file is stored. Right click the file and you’ll see the option “extract here”. Select this one.
Unlike the unzip command, the extract here options create a folder of the same name as the zipped file and all the content of the zipped files are extracted to this newly created folder. I am glad that this is the default behavior instead of extracting everything in the current directory.
There is also the option of ‘extract to’ and with that you can specify the folder where you want to extract the files.
That’s it. Now you know how to unzip a file in Linux. Perhaps you might also be interested in learning about using 7zip in Linux.
If you have questions or suggestions, do let me know in the comment section.
Like what you read? Please share it with others.
Как распаковать ZIP в Linux
В операционной системе Windows формат архивов ZIP считается чуть ли не стандартным, он даже поддерживается в этой операционной системе, что называется «из коробки». Если вы только перешли с Windows, то у вас, наверное, есть много таких архивов с различными файлами, также ZIP-архивы могут часто попадаться на просторах интернета. Поэтому работать с такими файлами в Linux вам однозначно придётся.
В этой небольшой статье мы рассмотрим, как распаковать ZIP Linux. Разберём несколько способов и воспользуемся несколькими утилитами, которые справятся с этой задачей.
Распаковка ZIP Linux
Формат ZIP был создан в 1989 году на замену очень медленному формату ARC. Здесь используется сжатие deflate, и на то время оно работало намного быстрее чем ARC. Исторически сложилось так, что стандартным форматом для Linux стали TAR и GZ — это усовершенствованные алгоритмы сжатия и архивации. Многие графические распаковки воспринимают и ZIP-файлы. Но они обрабатывают архивы не сами, а дают команду предназначенным для этого формата утилитам.
Утилита для распаковки ZIP называется unzip, она не всегда установлена по умолчанию. Но вы можете очень просто добавить её в свою систему из официальных репозиториев. Для этого в Ubuntu выполните:
sudo apt install unzip
А в системах, использующих формат пакетов Red Hat, команда будет выглядеть немного по-другому:
sudo yum install unzip zip
После установки большинство графических утилит для работы с архивами смогут распаковать архив ZIP Linux. Команда ZIP Linux установлена на случай, если вы захотите создавать ZIP-архивы.
Но этой утилите не нужны дополнительные оболочки для распаковки архива. Вы можете сделать всё прямо из консоли. Давайте рассмотрим синтаксис утилиты:
$ unzip опции файл_архива.zip файлы -x исключить -d папка
- файл архива — это тот файл, с которым нам предстоит работать;
- файлы — здесь вы можете указать файлы, которые нужно извлечь, разделять имена файлов пробелом;
- исключить — файлы, которые извлекать не нужно;
- папка — папка, в которую будет распакован архив.
Теперь рассмотрим опции утилиты, поскольку она позволяет не только распаковывать архивы, но и выполнять с ними определённые действия:
- -l — вывести список файлов в архиве;
- -t — протестировать файл архива на ошибки;
- -u — обновить существующие файлы на диске;
- -z — вывести комментарий к архиву;
- -c — извлекать файлы на стандартный вывод, перед каждым файлом будет выводиться его имя;
- -p — то же самое, только имя выводится не будет;
- -f — извлечь только те файлы, которые уже существуют на диске, и файлы в архиве более новые;
- -v — вывести всю доступную информацию;
- -P — указать пароль для расшифровки архива;
- -n — не перезаписывать существующие файлы;
- -j — игнорировать структуру архива и распаковать всё в текущую папку;
- -q — выводить минимум информации.
Все самые основные опции рассмотрели, теперь давайте рассмотрим несколько примеров работы с программой в терминале. Чтобы распаковать ZIP Linux в текущую папку, достаточно набрать:
Причём расширение указывать не обязательно. Протестировать архив можно с помощью опции -t:
unzip -tq имя_файла.zip
Вы можете протестировать все архивы в текущей папке, выполнив:
Если нужно распаковывать архив не в текущую папку, можно очень просто указать нужную:
unzip имя_файла.zip -d /tmp
Также можно распаковывать не весь архив, а только нужные файлы или файлы нужного формата:
unzip имя_файла.zip \*.txt -d /tmp
С помощью опции -l вы можете посмотреть список файлов в архиве:
Утилиту unzip разобрали и теперь вы с ней точно справитесь. Но я говорил, что мы рассмотрим несколько способов, как выполняется распаковка ZIP Linux. Поэтому дальше мы поговорим об утилите 7z.
Демонстрация работы утилит zip и unzip в терминале:
Как распаковать ZIP Linux с помощью 7z
7z — это кроссплатформенный набор утилит для работы с архивами. Кроме собственного формата, здесь поддерживается большое количество других, в том числе tar и zip. Плюс этой утилиты — в контекстное меню файлового менеджера будет добавлен пункт, с помощью которого вы сможете распаковывать или создавать архивы.
Для установки утилиты в Ubuntu или Debian выполните:
sudo apt install p7zip-full
А в Red Hat и CentOS:
sudo yum install p7zip
Теперь вы можете использовать контекстное меню вашего файлового менеджера, чтобы распаковать архив ZIP Linux. Также можно использовать программу в консоли. Синтаксис очень похож на unzip:
$ 7z команда опции имя_архива
Команда задаёт нужное действие. Нас будут интересовать только четыре команды:
- e (Extract) — извлечь файлы из архива;
- x eXtract — извлечь файлы из архива, сохраняя полный путь;
- l (List) — список файлов архива;
- t (Test) — проверить архив.
Теперь рассмотрим самые полезные опции:
- -o — указать папку для распаковки;
- -p — указать пароль;
- -x — не извлекать эти файлы;
- -w — указать рабочую директорию;
- -y — отвечать положительно на все вопросы;
Ну и рассмотрим примеры работы с утилитой. Сначала проверим содержимое архива:
Распаковываем архив, сохраняя структуру подкаталогов:
Или распаковываем все файлы в одну папку, игнорируя подкаталоги:
Или вы можете указать папку, в которую нужно распаковать файлы с помощью опции -o:
7z x файл.zip -o /tmp/
Выводы
В этой статье была рассмотрена распаковка ZIP Linux, как видите, это ненамного сложнее, чем распаковка стандартных архивов TAR. Мы рассмотрели два способа ,и теперь вы точно будете знать, что делать, когда столкнетесь с такой ситуацией. Если у вас остались вопросы, спрашивайте в комментариях!