Zip linux как заархивировать папку
Перейти к содержимому

Zip linux как заархивировать папку

  • автор:

zip and unzip in Linux

There are many utilities that can be used to archive/extract, compress/decompress files in Linux, mainly are: tar , gzip , bzip2 , zip , etc.
Before we use these utilities, it’s better to be clear about the differences between the meaning of archiving and compressing.

Archiving simply package several files together into a single file, there is no compress procedure involved implicitly, on the other side,
Compressing will package files together and apply some compressing algorithm to shrink the size of the resulting file.

A list of common archived files in Linux

  • .tar
  • .tar.gz
  • .tar.bz2
  • .tar.xz
  • .tar.Z
  • .tgz
  • .zip

Note:
.tar.gz and tar.bz2 are the two most common zipped file format in Linux, .gz implies gzip compressed file, while .bz2 implies bzip compressed (LZ77 algorith is applied) file.

The tar utility is used to create a single archive from several files and extract the files from an archinve.
The gzip , bzip2 or zip utility is used to compress a single file to smaller size.

tar, gzip, bzip2 are provided by default in most Linux/Unix distributions, zip utility may need a manual installation.

Compress Decompress List
gzip filename gzip -d *.gz, gunzip *.gz gzip -l *.gz
bzip2 filename bzip2 -d *.bz2, gunzip data.doc.bz2`
zip data.zip *.doc
zip -r data.zip data/
unzip *.zip unzip -l *.zip
tar -zcvf data.tgz *.doc
tar -zcvf data.tar.gz *.doc
tar -jcvf data.tbz2 *.doc
tar -zxvf data.tgz
tar -zxvf pics.tar.gz *.jpg
tar -jxvf data.bz2
tar -ztf *.tgz
tar -ztf *.bz2
tar -jtf *.bz2

Common options of tar

  • -c: create a new archive
  • -x: extract files from an archive
  • -t: list the contents of an archive
  • -r: append files to the end of an archive
  • -u: update

Note that the above five options are independent and therefore any two of them can not be used together (they can be used combined with other options but not each other).

-c or -x will be used when packaging or extracting.

  • -z, –gzip use gzip compress
  • -j, –bzip2 use bzip2 compress
  • -Z, –compress use for *.tar.Z
  • -v verbose
  • -O, –to-stdout extract files to standard output
  • -C, –directory Output directory

-f option is used to specify the archive name, this is a mandatory option for tar .

How to Use Unzip in Linux

Zipping and unzipping files eases a lot of complicated tasks like file transfer! In this tutorial, you’ll learn how to use unzip using Linux commands to improve your VPS workflow!

Zip is a commonly used compression function which is portable and easy to use. You can even unzip files in Windows, that were created in Linux!

Unzip is a utility that is not available on most Linux flavors by default, but can be easily installed. By creating .zip files you can match .tar.gz file compression!

What Is Zip Used For?

Below are a few scenarios in which you may choose to use zip files:

  • When you are frequently working between Windows and Unix based systems. Not only does this compress files but also is a file package utility. Works on multiple operating systems
  • To save bandwidth. If you have limited or restricted bandwidth, then zip can be used between two servers for file transfer
  • Transfers files quickly. Zip utility reduces file size, therefore reducing transfer time
  • Upload or download directories at a faster speed
  • Save disk space
  • Unzip password protected .zip files
  • Enjoy a good compression ratio

Remember, before taking advantage of Unzip on Linux, you’ll have to SSH into your virtual private server.

Debian and Ubuntu Systems

Installing unzip is easy! With Ubuntu and Debian use the command below to install unzip:

Sit back and wait a minute, until the installation is finished.

To create zip files, you’ll also have to install zip. You can do this with the following command:

Install Unzip on Linux CentOS and Fedora

This again is simple and can be done using below command:

Once the installation is complete you can check the path with the following command:

After you execute the direction in the command line, you should get an output that looks like this:

You can also confirm everything is installed properly by using the command bellow. It will give a verbose with unzip utility details.

How to Use Zip and Unzip in Linux

Now that we know how to install the utility, we can start learning the basic uses of it:

Create Zip Files in Linux

The basic syntax to create a .zip file is:

To test this, we created two files – ExampleFile.txt and ExampleFile1.txt. We’ll compress them into sampleZipFile.zip with the following command:

Using Linux to Unzip a file

The unzip command can be used without any options. This will unzip all files to the current directory. One such example is as shown below:

This by default will be unzipped in the current folder provided you have read-write access.

Remove a File from a .zip File

Once a .zip file is created, you can remove or delete files in it. So, if you want to remove ExampleFile.txt from the existing sampleZipFile.zip, then you can use the following command:

Once this command is executed, you can unzip the .zip file using:

Over here you will find that ExampleFile.txt has been removed and can’t be seen on extraction.

How to Update Zip Files

Once a .zip file is created, you can add a new file to an existing .zip file. Suppose a new file ExampleFile2.txt needs to be added to the already existing sampleZipFile.zip. You can do this with the command shown below:

Now if you extract sampleZipFile.zip, you will find the new file ExampleFile2.txt added to it.

Move a File to a Zip

You can easily move specific files to an the zip file. That means that after adding the files, they will be deleted from their original directories. This is mostly used when you have large file or directory, but need to conserve disk space. This is done by adding the -m option. A sample of this command would be:

Recursive Use of Zip on Linux

The -r option is used to recursively zip files. This option will compress all the files present within a folder. An example of such command is as shown below:

In the example, MyDirectory is a directory which has multiple files and sub-directories to be zipped.

Exclude Files in a Zip

While creating a .zip file, you can exclude unwanted files. This is done by using the -x option. Below is an example:

Here ExampleFile.txt will not be added to the sampleZipFile.zip.

Unzip to a Different Directory

In case you do not want to unzip to the current directory but want to specify a directory location, then this can also be done. Use the -d option to provide a directory path in the unzip command. An example of such command is as shown below:

Use Linux Unzip with Multiple Zip Files

If you want to unzip multiple zip files existing within your current working directory then you can use a command as shown below:

This command will unzip all the individual zip files.

Suppress Output When Using Unzip in Linux

By default, when we use the unzip command, the command prints list of all the files that are getting extracted. A summary of the extraction process is printed. In case you want to suppress these messages, then you can use the -q option. The command would be as shown below:

Exclude Files Using Unzip in Linux

In case you want to extract all files except for one, then you can use a similar command as shown below:

Here the command will unzip all files except excludedFile.txt.

You can also prevent specific file types from getting extracted. One such example is as shown below:

The above command will exclude all .png files from being extracted.

Using Unzip in Linux with Password Protected Files

A password protected .zip file can be decompressed using the -P option. A sample of such command is as shown below:

In the above command, Password will be the password for the .zip file.

Overriding Zip Files

When you unzip the same file again in the same location where the file was extracted, by default you will encounter a message asking whether you want to overwrite the current file, overwrite all files, skip extraction for the current file, skip extraction for all files or rename current file.

The options would be as shown below:

You can override these files by using the -o options. One such example is as shown below:

Caution should be taken while executing this command since this will completely overwrite the existing copies. Any changes made in the earlier copy will be overwritten.

Using Linux Unzip Without Overwriting Files

If you have unzipped a file and made some changes but you accidentally deleted a few files, then you can use this approach to restore it! Use the -n option to skip the extraction in case a file already exists. So effectively only files which do not exist will be extracted. An example of such a command is:

How to List the Content of a Zip in Linux

The -l option will list all the files within the .zip along with the timestamp and other basic details. An example of such command is:

Conclusion

That’s it, you’re introduced to all the essential functions of the zip and unzip Linux utilities. Start improving your file management right now!

Архивирование файлов в 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

Очень просто запомнить для упаковки используется опция cCreate, а для распаковки — 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

cpio -idv < /path/to 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. Мы рассмотрели только консольные команды, так сказать, чтобы была понятна суть. В графическом интерфейсе все еще проще. Если остались вопросы — задавайте их в комментариях.

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

How to zip a folder in Ubuntu Linux / Debian Linux

Smit Pipaliya

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. Compressed (zipped) files take up less disk space and can be transferred from one to another machine more quickly than uncompressed files. Zip files can be easily extracted in Windows, macOS, and Linux using the utilities available for all operating systems.

Unzip is a utility that is not available on most Linux flavors by default, but can be easily installed. By creating .zip files you can match .tar.gz file compression!

This quick blog shows you how to Zip (compress) files and directories in Linux using the zip command.

What Is Zip Used For?

Below are a few scenarios in which you may choose to use zip files:

  • When you are frequently working between Windows and Unix-based systems. Not only does this compress files but also is a file package utility. Works on multiple operating systems
  • To save bandwidth. If you have limited or restricted bandwidth, then zip can be used between two servers for file transfer
  • Transfers files quickly. Zip utility reduces file size, therefore reducing transfer time
  • Upload or download directories at a faster speed
  • Save disk space
  • Unzip password-protected .zip files
  • Enjoy a good compression ratio

Remember, before taking advantage of Unzip on Linux, you’ll have to SSH into your virtual private server.

Install Zip on Debian and Ubuntu Systems

Installing unzip is easy! With Ubuntu and Debian use the command below to install unzip:

Sit back and wait a minute, until the installation is finished.

To create zip files, you’ll also have to install zip. You can do this with the following command:

Install Unzip on Linux CentOS and Fedora

This again is simple and can be done using the below command:

Once the installation is complete you can check the path with the following command:

After you execute the direction in the command line, you should get an output that looks like this:

You can also confirm everything is installed properly by using the command below. It will give a verbose with unzip utility details.

How to Use Zip and Unzip in Linux

Now that we know how to install the utility, we can start learning its basic uses of it:

zip Command

Zip is a command-line utility that helps you create Zip archives.

The zip command takes the following syntax form:

To create a Zip archive in a specific directory, the user needs to have write permissions on that directory.

Zip files do not support Linux-style ownership information. The extracted files are owned by the user that runs the command. To preserve the file ownership and permissions, use the tar command.

The zip utility is not installed by default in most Linux distributions, but you can easily install it using your distribution package manager.

Create Zip Files in Linux

The basic syntax to create a .zip file is:

To test this, we created two files — ExampleFile.txt and ExampleFile1.txt. We’ll compress them into sampleZipFile.zip with the following command:

Using Linux to Unzip a file

The unzip command can be used without any options. This will unzip all files to the current directory. One such example is as shown below:

This by default will be unzipped in the current folder provided you have read-write access.

Remove a File from a .zip File

Once a .zip file is created, you can remove or delete files in it. So, if you want to remove ExampleFile.txt from the existing sampleZipFile.zip, then you can use the following command:

Once this command is executed, you can unzip the .zip file using:

Over here you will find that ExampleFile.txt has been removed and can’t be seen on extraction.

How to Update Zip Files

Once a .zip file is created, you can add a new file to an existing .zip file. Suppose a new file ExampleFile2.txt needs to be added to the already existing sampleZipFile.zip. You can do this with the command shown below:

Now if you extract sampleZipFile.zip, you will find the new file ExampleFile2.txt added to it.

Move a File to a Zip

You can easily move specific files to a zip file. That means that after adding the files, they will be deleted from their original directories. This is mostly used when you have a large file or directory, but need to conserve disk space. This is done by adding the -m option. A sample of this command would be:

Recursive Use of Zip on Linux

The -r option is used to recursively zip files. This option will compress all the files present within a folder. An example of such a command is shown below:

In the example, MyDirectory is a directory that has multiple files and sub-directories to be zipped.

Exclude Files in a Zip

While creating a .zip file, you can exclude unwanted files. This is done by using the -x option. Below is an example:

Here ExampleFile.txt will not be added to the sampleZipFile.zip.

Unzip to a Different Directory

In case you do not want to unzip to the current directory but want to specify a directory location, then this can also be done. Use the -d option to provide a directory path in the unzip command. An example of such a command is shown below:

Use Linux Unzip with Multiple Zip Files

If you want to unzip multiple zip files existing within your current working directory then you can use a command as shown below:

This command will unzip all the individual zip files.

Creating a Password Protected ZIP file

If you have sensitive information that needs to be stored in the archive, you can encrypt it using the -e option:

Creating Split Zip File

Imagine you want to store the Zip archive on a file hosting service that has a file size upload limit of 1GB, and your Zip archive is 5GB.

You can create a new split Zip file using the -s option followed by a specified size. The multiplier can be k (kilobytes), m (megabytes), g (gigabytes), or t (terabytes).

The command above will keep creating new archives in a set after it reaches the specified size limit.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *