- How to Create and Extract Zip Files to Specific Directory in Linux
- Create Zip Archive File in Linux
- Extract Zip File to Specific or Different Directory
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- 3.1 Archiving Files from the Linux Command Line
- Compress or Not Compressed
- Using Tar
- Creating a TAR file
- Viewing a TAR file
- Extracting a TAR file
- Compressing the archives
- Архивирование файлов в Linux
- Архивирование в Linux
- Сжатие архивов в Linux
- Выводы
How to Create and Extract Zip Files to Specific Directory in Linux
In one of our several articles about the tar command, we showed you how to extract tar files to a specific or different directory in Linux. This short guide explains to you how to extract/unzip .zip archive files to a specific or different directory in Linux.
Zip is a simple, cross-platform file packaging and compression utility for Unix-like systems including Linux and Windows OS; plus many other operating systems. The “zip” format is a common archiving file format used on Windows PC’s and most importantly, it enables you to specify the compression level between 1 and 9 as an option.
Create Zip Archive File in Linux
To create a .zip (packaged and compressed) file from the command line, you can run a similar command like the one below, The -r flag enables recursive reading of files directory structure.
Create Zip File in Linux
To unzip the tecmint_files.zip archive file you have just created above, you can run the unzip command as follows.
The above command will extract the files into the current working directory. What if you want to send the unzipped files into a specific or different directory – you can learn this in the next section.
Extract Zip File to Specific or Different Directory
To extract/unzip .zip archive files to specific or different directory from the command line, include the -d unzip command flag as shown below. We will use the same example above to demonstrate this.
This will extract the .zip file content into the /tmp directory:
Extract Zip Files to Specific Directory
For more usage information, read zip and unzip command man pages.
You may also like to read the following related articles.
In this short article, we have explained how to extract/unzip .zip archive files to a specific or different directory in Linux. You can add your thoughts to this article via the feedback form below.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник
3.1 Archiving Files from the Linux Command Line
I am sure if you have not already come across tar and gz files within Linux it will not be long before you become acquainted with each other. Of course, these file make up just a part of what we mean when we talk about archiving files from the Linux command line. Spending just a little time with Linux you will soon come across TAR files of some type, be they TAR, TGZ , TAR.GZ or some other format. The TAR archive, or Tape Archive, file is an oldie but a goodie having passed across from UNIX into Linux. The archive itself is a single file that can represent many files.
Compress or Not Compressed
These tar files do not have to compressed but they often are. However, even if it is not zipped up it will often consume less disk space than the files stored individually. Consider the following screenshot where we first look at the size of the directory and then create a tar archive file, uncompressed, and view the size of the tar file: it is smaller:
The output shows the directory to be 52K and the tar archive to be just 20K and no compression has been used. This relates to the way the filesystem uses blocks of disk space. Each new file has to start with its own new block. Often the block size is 4KB; this means for each 1KB file, for instance, will consume 4KB of disk space. If we combine these files into one file, a TAR file, then less space can be used to store the same amount of data.
Using Tar
The three main options we have with tar are:
- -c : create a new archive
- -x : extract an archive
- -t : verify or test and archive
Creating a TAR file
From the previous graphic we can see the creation of the TAR file. We normally include .tar as the last four characters of the file name so we easily identify this type of file. The option -f specifies the file name and must be followed by the same.
In this example we archive the labs directory within current directory. The target file for the archive is: labs.tar, also within the current directory. The source directory labs remains intact and unaffected by the operation other than updating the last accessed time attribute of each file included in the archive. In order to backup a file it has to be read, hence the last accessed time of each file we archive will be updated to the time of the backup.
Viewing a TAR file
Once we have created the file we can verify the file contents with the -t option:
Incidentally, a large TAR file may be read directly with the command less , this allows for the file contents to be paged through without the explicitly use of tar and less together.
Extracting a TAR file
To extract the complete archive the command is simple and makes use of the -x option:
The files will expand within the current directory unless the option -P is used both when the archive is created and expanded, in which case the files are expanded to the full path of the original files. If there are concerns that you may overwrite files then a couple of options exist that may help
- -k : prevents existing files being overwritten
- –keep-newer-files : will not overwrite if the target file is newer than the archive file
Should we want to extract only a single file or certain files from the archive we could use code similar to the following:
This would extract just the single file from the archive, we can use the -t option if we need to confirm the path too the file in the archive.
Compressing the archives
These archives can be compressed and uncompressed within the same TAR process. Using the options:
- -z : the use gzip for compression and gunzip for decompressing the file
- -j | uses bzip2 for compression and bunzip2 for decompressing.
The first command creates the zipped archive and the second extracts the archive. The option -z must be used in both cases and also with -t for viewing. If we had used the option -j in the first instance then -j must be used to access the archive in future. A good naming standard is useful here so we know how to open or view the file; commonly these endings are used for file names:
- .tar : indicates a uncompressed file
- .tar.gz or .tgz : indicates a file compressed with gzip
- .tar.bz2 or .tbz2 | indicates a file where bzip2 was used to compress the archive
Ultimately, though, we can use the command file (/usr/bin/file) to identify the type of archive we have:
This will identify the compression used, if any and confirm that the file is a TAR archive.
Источник
Архивирование файлов в Linux
В наши дни мы сталкиваемся с файлами архивов очень часто и на всех платформах: Windows, Mac или Linux. Это могут быть программы, резервные копии систем или баз данных или просто архив файлов. Нам также часто приходится создавать свои архивы в Linux, чтобы передать несколько файлов друзьям или загрузить на файлообменник. В виде архивов распространяются пакеты программ, исходные коды, а также много других файлов, распространяемых на просторах интернета. Научиться выполнять архивирование файлов в Linux через терминал очень важно, возможно это вам понадобиться, когда не будет доступа к графическому интерфейсу, или просто со временем в терминале станет более приятно работать.
В этой инструкции я хочу подробно рассмотреть утилиты для архивирования в Linux, мы рассмотрим не только самую популярную и универсальную утилиту — tar, но и другие менее известные, а также популярные алгоритмы сжатия.
Архивирование в Linux
Важно отметить, что архивирование в linux это не одно и то же что и сжатие файлов linux. Архивирование — это объединение нескольких небольших файлов в один, с целю более удобной последующей передачи, хранения, шифрования или сжатия. Как я уже сказал, архивация выполняется специальными утилитами. Мы не будем трогать архивацию файлов в графическом интерфейсе, вы с ними разберетесь сами, наша тема — терминал.
Самой популярной для Linux утилитой для архивации есть tar. Она используется почти везде, для архивации исходников, упаковки пакетов. Для сжатия используются другие утилиты, в зависимости от алгоритма сжатия, например, zip, bz, xz, lzma и т д. Сначала выполняется архивация, затем сжатие, отдельными программами. Автоматический запуск некоторых утилит сжатия для только что созданного архива поддерживается в tar и других подобных программах с помощью специальных опций.
Также полезной возможностью архивации есть шифрование. Но теперь давайте рассмотрим какие существуют утилиты, с помощью которых выполняется архивирование файлов linux и как ими пользоваться.
Tar — это стандартная утилита, с помощью которой выполняется архивирование файлов Linux. Постепенно из небольшой программы архивации она превратилась в мощный инструмент, поддерживающий работу со многими вариантами архивов и алгоритмами сжатия. Программа поддерживает большое количество параметров. Давайте рассмотрим ее синтаксис и основные параметры:
$ tar опции f файл_для_записи /папка_файлами_для_архива
А теперь разберем основные опции:
- A — добавить файл к архиву
- c — создать архив в linux
- d — сравнить файлы архива и распакованные файлы в файловой системе
- j — сжать архив с помощью Bzip
- z — сжать архив с помощью Gzip
- r — добавить файлы в конец архива
- t — показать содержимое архива
- u — обновить архив относительно файловой системы
- x — извлечь файлы из архива
- v — показать подробную информацию о процессе работы
- f — файл для записи архива
- -C — распаковать в указанную папку
- —strip-components — отбросить n вложенных папок
Теперь давайте рассмотрим архивирование файлов в Linux. Чтобы создать архив используйте такую команду:
tar -cvf archive.tar.gz /path/to/files
А чтобы распаковать архив tar linux:
tar -xvf archive.tar.gz
Очень просто запомнить для упаковки используется опция c — Create, а для распаковки — x — eXtract.
Сжатый архив создается точно так же, только с опцией -z, это в случае, если использовалось шифрование gizp, если нужно bzip то применяется опция -j:
tar -zcvf archive.tar.gz /path/to/files
$ tar -zxvf archive.tar.gz
Например, рассмотрим как заархивировать папку в Linux:
tar -zcvf home.tar.gz
Хотя можно поступить по-другому, тот же архив мы получим если сначала создать обычный архив с помощью tar, а потом сжать его утилитой для сжатия, только здесь мы получаем больше контроля над процессом сжатия:
Также можно убрать сжатие:
Утилиты сжатия мы рассмотрим ниже.
Чтобы добавить файл в архив используйте:
tar -rvf archive.tar file.txt
Для извлечения одного файла синтаксис тот же:
tar -xvf archive.tar file.txt
Можно извлечь несколько файлов по шаблону соответствия с помощью параметра wildcard, например, извлечем все php файлы:
tar -xvf archive.tar —wildcards ‘*.php’
По умолчанию распаковать архив tar linux можно в текущую папку с именем архива, чтобы распаковать в нужную папку используйте ключ -C:
tar -xvf archive.tar -C /path/to/dir
Стандартную утилиту рассмотрели, теперь кратко рассмотрим ее альтернативы. Их не так много, и большинство из них уже устаревшие.
Shar позволяет создавать самораспаковывающиеся архивы. По сути, это скрипт оболочки, и для распаковки ему необходима оболочка Bash или другая совместимая с Bourne Shell. У Shar есть несколько преимуществ, но также он потенциально небезопасный, так как архив представляет собой исполняемый файл.
- -o — сохранять архив в файл вместо стандартного вывода
- -l — ограничить размер выходного файла
- -L — ограничить размер выходного файла и разбить его на части
- -n — имя архива не будет включено в заголовок
- -a — разрешить автоматическую генерацию заголовков
Примеры использования shar для того чтобы заархивировать папку linux:
Создаем shar архив:
shar file_name.extension > filename.shar
Распаковываем shar архив:
ar — утилита для создания и управления архивами. В основном используется для архивации статических библиотек, но может быть использована для создания любых архивов. Раньше использовалась довольно часто но была вытеснена утилитой tar. Сейчас используется только для создания и обновления файлов статических библиотек.
- — d — удалить модули из архива
- — m — перемещение членов в архиве
- — p — напечатать специфические члены архива
- — q — быстрое добавление
- — r — добавить члена к архиву
- — s — создать индекс архива
- — a — добавить новый файл к существующему архиву
Теперь рассмотрим примеры использования. Создадим статическую библиотеку libmath.a из объектных файлов substraction.o и division.o:
ar cr libmath.a substraction.o division.o
Теперь извлечем файлы из архива:
Таким образом, можно распаковать любую статическую библиотеку.
cpio — означает Copy in and out (скопировать ввод и вывод). Это еще один стандартный архиватор для Linux. Активно используется в менеджере пакетов Red Hat, а также для создания initramfs. Архивация в Linux для обычных файлов с помощью этой программы не применяется.
- -a — сбросить время обращения к файлам после их копирования
- -A — добавить файл
- -d — создать каталоги при необходимости
Пример использования. Создаем cpio архив:
file1.o file2.o file3.o
ls | cpio -ov > /path/to/output_folder/obj.cpio
Архивирование папки linux выполняется также само.
Сжатие архивов в Linux
Как создать архив в linux рассмотрели. Теперь давайте поговорим о сжатии. Как я говорил, для сжатия используются специальные утилиты. Рассмотрим кратко несколько из них
Чаще всего применяется Gzip. Это стандартная утилита сжатия в Unix/Linux. Для декомпрессии используется gunzip или gzip -d Сначала рассмотрим ее синтаксис:
$ gzip опции файл
$ gunzip опции файл
Теперь разберем опции:
- -c — выводить архив в стандартный вывод
- -d — распаковать
- -f — принудительно распаковывать или сжимать
- -l — показать информацию об архиве
- -r — рекурсивно перебирать каталоги
- -0 — минимальный уровень сжатия
- -9 — максимальный уровень сжатия
Примеры использования вы уже видели в описании утилиты tar. Например, выполним сжатие файла:
gzip -c файл > архив.gz
А теперь распакуем:
gunzip -c архив.gz
Но чтобы сжать папку в Linux вам придется сначала заархивировать ее с помощью tar, а уже потом сжать файл архива с помощью gzip.
bzip2 — еще одна альтернативная утилита сжатия для Linux. Она более эффективная чем gzip, но работает медленнее. Для распаковки используйте утилиту bunzip2.
Описывать опции bzip2 я не буду, они аналогичны gzip. Чтобы создать архив в Linux используйте:
В текущем каталоге будет создан файл file.bz2
Новый и высокоэффективный алгоритм сжатия. Синтаксис и опции тоже похожи на Gzip. Для распаковки используйте unlzma.
Еще один высокоэффективный алгоритм сжатия. Обратно совместимый с Lzma. Параметры вызова тоже похожи на Gzip.
Кроссплатформенная утилита для создания сжатых архивов формата zip. Совместимая с Windows реализациями этого алгоритма. Zip архивы очень часто используются для обмена файлами в интернете. С помощью этой утилиты можно сжимать как файлы, так и сжать папку linux.
$ zip опции файлы
$ unzip опции архив
- -d удалить файл из архива
- -r — рекурсивно обходить каталоги
- -0 — только архивировать, без сжатия
- -9 — наилучший степень сжатия
- -F — исправить zip файл
- -e — шифровать файлы
Чтобы создать Zip архив в Linux используйте:
zip -r /path/to/files/*
А для распаковки:
Как видите архивирование zip в Linux не сильно отличается от других форматов.
Выводы
Теперь вы знаете все что нужно об архивации файлов в Linux. Мы рассмотрели только консольные команды, так сказать, чтобы была понятна суть. В графическом интерфейсе все еще проще. Если остались вопросы — задавайте их в комментариях.
Источник