How to zip file in linux

How to zip file in linux

How to zip a file in Ubuntu

I use Ubuntu. When I have to zip a folder I use the command zip folder.zip folder/

The result is an empty zipped folder! Where did all the files in the folder go?

How to zip file in linux. Смотреть фото How to zip file in linux. Смотреть картинку How to zip file in linux. Картинка про How to zip file in linux. Фото How to zip file in linux

4 Answers 4

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

How to zip file in linux. Смотреть фото How to zip file in linux. Смотреть картинку How to zip file in linux. Картинка про How to zip file in linux. Фото How to zip file in linux

If zip command is not working then you need to install zip first. Here is the command which will install zip, gzip and tar.

then you can zip, gzip or tar. zip the folder :

Here are some more related useful commands :

check out solution below: You can create a simple zip file with zip command without using any options.

For example to create a zip file of text files first_file.txt, second_file.txt and third_file.txt run below command:

The output should be:

for more information visit

How to zip file in linux. Смотреть фото How to zip file in linux. Смотреть картинку How to zip file in linux. Картинка про How to zip file in linux. Фото How to zip file in linux

Let’s take the question «How to zip a file in ubuntu» as «how to compress a file in Ubuntu».

Please note that you have the following trade-offs:

Also, you can distinguish creating an archive (multiple files in one file) and compressing it. If you see it as a two-step process ((1) Archive (2) compress) you can solve them independently.

Please also note that different compression algorithms shine in different scenarios. There is no single algorithm that is always best («no free lunch»)

Архивирование файлов в Linux

В наши дни мы сталкиваемся с файлами архивов очень часто и на всех платформах: Windows, Mac или Linux. Это могут быть программы, резервные копии систем или баз данных или просто архив файлов. Нам также часто приходится создавать свои архивы в Linux, чтобы передать несколько файлов друзьям или загрузить на файлообменник. В виде архивов распространяются пакеты программ, исходные коды, а также много других файлов, распространяемых на просторах интернета. Научиться выполнять архивирование файлов в Linux через терминал очень важно, возможно это вам понадобиться, когда не будет доступа к графическому интерфейсу, или просто со временем в терминале станет более приятно работать.

Архивирование в Linux

Самой популярной для Linux утилитой для архивации есть tar. Она используется почти везде, для архивации исходников, упаковки пакетов. Для сжатия используются другие утилиты, в зависимости от алгоритма сжатия, например, zip, bz, xz, lzma и т д. Сначала выполняется архивация, затем сжатие, отдельными программами. Автоматический запуск некоторых утилит сжатия для только что созданного архива поддерживается в tar и других подобных программах с помощью специальных опций.

Также полезной возможностью архивации есть шифрование. Но теперь давайте рассмотрим какие существуют утилиты, с помощью которых выполняется архивирование файлов linux и как ими пользоваться.

$ tar опции f файл_для_записи /папка_файлами_для_архива

А теперь разберем основные опции:

Теперь давайте рассмотрим архивирование файлов в Linux. Чтобы создать архив используйте такую команду:

А чтобы распаковать архив tar linux:

Например, рассмотрим как заархивировать папку в Linux:

Хотя можно поступить по-другому, тот же архив мы получим если сначала создать обычный архив с помощью tar, а потом сжать его утилитой для сжатия, только здесь мы получаем больше контроля над процессом сжатия:

Также можно убрать сжатие:

Утилиты сжатия мы рассмотрим ниже.

Чтобы добавить файл в архив используйте:

Для извлечения одного файла синтаксис тот же:

Можно извлечь несколько файлов по шаблону соответствия с помощью параметра wildcard, например, извлечем все php файлы:

Стандартную утилиту рассмотрели, теперь кратко рассмотрим ее альтернативы. Их не так много, и большинство из них уже устаревшие.

Shar позволяет создавать самораспаковывающиеся архивы. По сути, это скрипт оболочки, и для распаковки ему необходима оболочка Bash или другая совместимая с Bourne Shell. У Shar есть несколько преимуществ, но также он потенциально небезопасный, так как архив представляет собой исполняемый файл.

Примеры использования shar для того чтобы заархивировать папку linux:

Создаем shar архив:

shar file_name.extension > filename.shar

Распаковываем shar архив:

Теперь рассмотрим примеры использования. Создадим статическую библиотеку libmath.a из объектных файлов substraction.o и division.o:

ar cr libmath.a substraction.o division.o

Теперь извлечем файлы из архива:

Таким образом, можно распаковать любую статическую библиотеку.

Пример использования. Создаем cpio архив:

file1.o file2.o file3.o

Архивирование папки linux выполняется также само.

Сжатие архивов в Linux

Как создать архив в linux рассмотрели. Теперь давайте поговорим о сжатии. Как я говорил, для сжатия используются специальные утилиты. Рассмотрим кратко несколько из них

$ gzip опции файл

$ gunzip опции файл

Теперь разберем опции:

Примеры использования вы уже видели в описании утилиты tar. Например, выполним сжатие файла:

А теперь распакуем:

Но чтобы сжать папку в Linux вам придется сначала заархивировать ее с помощью tar, а уже потом сжать файл архива с помощью gzip.

Описывать опции bzip2 я не буду, они аналогичны gzip. Чтобы создать архив в Linux используйте:

В текущем каталоге будет создан файл file.bz2

Новый и высокоэффективный алгоритм сжатия. Синтаксис и опции тоже похожи на Gzip. Для распаковки используйте unlzma.

Еще один высокоэффективный алгоритм сжатия. Обратно совместимый с Lzma. Параметры вызова тоже похожи на Gzip.

Кроссплатформенная утилита для создания сжатых архивов формата zip. Совместимая с Windows реализациями этого алгоритма. Zip архивы очень часто используются для обмена файлами в интернете. С помощью этой утилиты можно сжимать как файлы, так и сжать папку linux.

$ zip опции файлы

$ unzip опции архив

Чтобы создать Zip архив в Linux используйте:

А для распаковки:

Как видите архивирование zip в Linux не сильно отличается от других форматов.

Выводы

How do I make a zip file on linux?

5 Answers 5

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

Even if it functions well I would like to propose you 7z(http://www.7-zip.org/).

It has a better compression and it is opensource, GNU LGPL license, freely available for windows,linux,BSD.

BTW it creates/opens 7z, XZ, BZIP2, GZIP, TAR, ZIP and WIM,
and open unpack only: ARJ, CAB, CHM, CPIO, CramFS, DEB, DMG, FAT, HFS, ISO, LZH, LZMA, MBR, MSI, NSIS, NTFS, RAR, RPM, SquashFS, UDF, VHD, WIM, XAR and Z.

[They should pay me for advertisement :-)]

On linux, although it can zip you really should instead be using :

where archive_name.tar will be the the compressed version of the input dir /path/to/directory_to_compress

How to zip file in linux. Смотреть фото How to zip file in linux. Смотреть картинку How to zip file in linux. Картинка про How to zip file in linux. Фото How to zip file in linux

I think this is gonna help you

This should be quite easy and short
compressing

For more interested in knowing usage options

Typically one uses tar to create an uncompressed archive and either gzip or bzip2 to compress that archive. The corresponding gunzip and bunzip2 commands can be used to uncompress said archive, or you can just use flags on the tar command to perform the uncompression.

If you are referring specifically to the Zip file format, you can simply use the zip and unzip commands.

or to zip a directory

this unzips it in your current working directory.

Linux zip folder | 16 practical Linux zip command examples

Table of Contents

Linux Zip Command Examples

In this tutorial I will share various Unix and Linux zip command examples and scenarios to understand how to zip a folder and how to create a zip file.

zip is a compression and file packaging utility for Unix, VMS, MSDOS, OS/2, Windows 9x/NT/XP, Minix, Atari, Macintosh, Amiga, and Acorn RISC OS.

Pre-requisite:

Before we zip a folder and create a zip file in Linux or Unix, we must install the zip and unzip utility.

Install zip

In some Linux and Unix variants, zip is installed by default with operating system. You can also manually install zip utility by using yum

Install unzip

Similarly to be able to unzip files and folders in Linux or Unix you will need unzip utility

1. How to zip a folder with multiple files Linux

In this Linux zip command example you will learn, how to zip a folder with multiple files or all files from the current working directory and store the archive at the same location. List the files which you wish to zip using ls command

Let’s take this Linux zip command example. Here we will zip multiple files or rather all the files from current working directory.

Verify the newly created zip file ( rpms.zip )

Now in the last zip command example we archived all the files present inside /tmp/files directory. Now I wish to zip all files except one or some selected files. In this case you must provided the name of the files which you wish to archive so zip will only consider those files for compression and archive.

So now our archive only contains two files which we provided as input and the archive was stored in the same path.

2. How to create a zip file by excluding some files

Below Linux zip command example will show how to create a zip file with all files except some files.

To create zip a folder with all files except some files using a regex, here all file names starting with bc will be excluded

To create a zip folder by excluding multiple files

3. How to zip a folder by compressing directory and sub-directories

By default zip command will only compress files. if you attempt to compress directory, then you may get below output

As you see the stored content was 0%. So how to zip a folder or directory?

4. How to display zip archive content

5. How to zip a folder with password protection

Now how to unzip files? If you try to unzip to directory, the zip file will prompt for password. Without password you will not be able to unzip to directory.

6. How to update or modify existing file in zip archive

You can modify zip file content here.

Now add some more content to the existing file

7. How to add files to existing zip archive

8. How to list zip archive contents without extracting

9. How to create a zip file without complete path (Store only the file name)

By default when we create a zip archive, it stores the relative path for the archived content. Lets take this Linux zip command example which stores the relative path of files:

List and verify the zip archive content.

10. How to create a zip file and delete original files after archiving

As expected our source directory is also deleted after archiving

11. How to zip a folder with higher compression level

With the default compression level, when we create a zip folder, the compressing of 1668 rpms the zip tool took

The original size of the source location was

which after compression is 842M so we saved

Now with higher level of compression, zip took additional 3 seconds to complete the compression but we only save 1MB overall in our archive so the advantage was not very high compared to the time we invested.

12. How to copy files between two zip archives

Here in this Linux zip command example we copy files between two zip archives, I have an input archive with below content

I will copy one of the rpm to another new archive

Verify the content of the output_archive

13. Linux zip directory and remove files from zip archive

Let us take this Linux zip command example. Here I have a Linux zip archive with below content

Verify the content of the archive

14. Linux zip folder and preserve symbolic links

This can avoid multiple copies of files being included in the archive as zip re curses the directory trees and accesses files directly and by links.

Let’s take this Linux zip command example. Here I have created a dummy file inside my root’s home folder and added some content.

Create a symlink to this dummy file

Verify the symlink

I will create a dummy location to extract the archive and verify the symlink

Unzip to directory using unzip command

Unzip to directory the newly created archive using unzip to make sure zip was able to preserve and store symbolic links

Next verify the symlink content.

15. How to create a zip file and compress with bzip2

Extract content using unzip command

Extract the content using unzip to directory

16. How to zip a folder and later split zip archive

Let’s use this Linux zip command example to create a zip folder with split enable. I have Packages directory with files having size of 902MB. Here I will create zip archive

The last file as you see is of 36MB while all the other archive is of 200MB which we had used as the split size

Lastly I hope the steps from the article to compress and archive using zip command and cover scenarios life zip multiple files and folders, zip all files except some files and folders, compress directory and preserve symbolic links, remove files from zip archive, zip delete original files in Linux and Unix was helpful. So, let me know your suggestions and feedback using the comment section.

References:

Related Posts

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

How to zip file in linux. Смотреть фото How to zip file in linux. Смотреть картинку How to zip file in linux. Картинка про How to zip file in linux. Фото How to zip file in linux

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

How to Zip a File in Linux with easy examples

In this tutorial, I will give you a complete guide and every important option listed on «How to Zip a File in Linux». Zipping a file or directory in Linux helps to take backup and save disk space by compressing unused files. I am using Ubuntu Linux 20.04 to showcase all examples in this post.

What is Zip

Zip is basically a file packaging and compression utility for almost every operating system, whether it’s any Linux flavour, Windows, Mac and even some RISC systems.

It is always installed on all Linux or Unix system by default except few cases. It is analogous to a combination of two commands tar and compress.

Generally, zip program puts one or more compress files in Linux into a single zip archive along with meta-information about the file.

The compression ratio of zip files in Linux is around 2:1 or 3:1 are common of text files and it varies for different file types. Single zip command can put an entire directory structure into a zip archive.

In case of large archives greater than 4GB, zip automatically uses zip64 extension. Zip is compatible with Pkzip and Pkunzip utilities as well.

Zip also now supports bzip2 compression utility, if the bzip2 library generally gets compiled with zip.

Unzip and tar are two companion utilities. Unzip unpacks or decompress zip archive and tar is used to take backup.

Pre-requisite of Zip utility

There is no special pre-requisite, the only thing you need to do is to check whether zip is installed in Linux or not.

Run this command. it will install zip and unzip utility if it’s not there. If it’s already installed, it will upgrade or do nothing as shown in the output.

It shows zip and unzip utility is already on the newest version. so you are done with installing zip and unzip till this point and you are ready to explore the world of Compress files and folder in Linux.

If you have Centos or Fedora distro. Run below-mentioned commands to install zip and unzip

I will explain zipping files in Linux using two options

How to zip a file in Linux GUI

Step1:-

Go to the directory where file or folders resides.

Step2:-

Step3:-

Give archive name. I will give sample-zip as an example.

Step4:-

How to zip a file in Linux terminal

Let’s see different options and examples of Zip program one by one.

Example 1:- How to compress or zip files in Linux

output
adding: file1 (deflated 69%)
adding: file2 (deflated 69%)
dev@test:

File name and compression % is reflected in the output. As you can see I have not included .zip extension, still by default command add that into output-file name. In my case «test-zip.zip«.

if you want to suppress this output of zip command, you can use -q option.

There may be the case, if you forgot to give output-file-name in zip command, then it will by-default pick the first file name as the output file and second file into zip. So below mentioned example also show, how to zip multiple files in Linux.

Output
adding: file2 (deflated 69%)
dev@test:

Example 2:- How to zip folder and subfolders in Linux

Output
adding: sample/ (stored 0%)
adding: sample/file2 (deflated 69%)
adding: sample/file1 (deflated 69%)
dev@test:

Compression levels in Zip utility

Example 3:- How to use compression level 0 & 9

Output
adding: sample/ (stored 0%)
adding: sample/file2 (stored 0%)
adding: sample/file1 (stored 0%)

output shows, if I select 0 as compression level, there is no compression at all during zipping of the files or folder.

Output
adding: sample/ (stored 0%)
adding: sample/file2 (deflated 69%)
adding: sample/file1 (deflated 69%)
dev@test:

if Zip found that file can’t be compressed, it just archives and stores it as-is without compress file in Linux.

Example 4:- How to zip a file in Linux using bzip2 utility

Output
adding: sample/ (stored 0%)
adding: sample/file2 (bzipped 74%)
adding: sample/file1 (bzipped 74%)
dev@test:

So bzipping files may result in more space-saving but changing compression level or using bzip2 to get more space-saving comes with penality of CPU resources and it will take more time to compress in case of a large number of files in Linux.

But it will definitely save network resources if you are planning to transfer or send it over the internet.

Zip and encrypt a file in Linux

Many times you need to store or need to send/transfer a file to someone and it may contain sensitive or personal data.

To avoid misuse of this file, you can always encrypt or enable password on archive file using -e option.

Example 5:- How to enable password on the zip file in Linux

Output asking for password
Enter password:
Verify password:
adding: sample/ (stored 0%)
dev@test:

Create a split zip file in Linux

There may be a case when you have a big file to archive and you need to split it due to storage or upload limits on FTP site or file hosting vendor.

Example 6:- How to create a split zip file in Linux

I have a zip file of Ubuntu 20.04 iso image with name ubuntu.zip (2.5G) and I will split it into 1g archive files.

Have a look on split.zip, split.z01 and split.z02

Now when you have split the file using zip and you will be thinking of joining this on target. Don’t worry, I won’t let you scratch your head.

Example 7:- How to add or combine a split zip file in Linux

Go to the directory where you have kept split files

Output
-rw-r—r— 1 dev dev 1.0G Jun 18 18:03 split.z02
-rw-r—r— 1 dev dev 504M Jun 18 18:04 split.zip
-rw-r—r— 1 dev dev 1.0G Jun 18 18:04 split.z01

now Join split zip files.

Validate the size in output

Example 8:- How to update a zip file in Linux

let’s assume you forgot to add one file into a zip or want to add more files to existing zip, then -u option can help. In this example, I will add file4 to existing test.zip file.

Output
adding: file4 (deflated 69%)

Example 9:- How to exclude a file from a zip archive in Linux

Currently, I have three files in the sample directory

total 264K
-rw-r—r— 1 dev dev 88K Jun 17 21:51 file1
-rw-r—r— 1 dev dev 88K Jun 17 23:21 file2
-rw-r—r— 1 dev dev 88K Jun 18 18:20 file3

let’s exclude file3, only 2 files archived.

Output
adding: file1 (deflated 69%)
adding: file2 (deflated 69%)
dev@test:

Example 10:- Verbose mode in zipping files in Linux

if you want to see the progress, -v option known as verbose or diagnostic version info can be helpful especially when you are working with a large number of files.

Example 11:- Working with wildcards to compress files in Linux

The mostly used wildcard is an asterisk(*) in this world, in my view, Zip utility supports this helpful wildcard character. No need to type each and every file name.

Output
adding: file1 (deflated 69%)
adding: file2 (deflated 69%)
adding: file3 (deflated 69%)
dev@test:

Some common issues and error codes during zipping in Linux

0 normal; no errors or warnings detected, means archiving done

2 unexpected end of zip file in Unix.

11 read or seek error, Unable to read the file

12 zip has nothing to do, Some action is missing

13 missing or empty zip file

14 error writing to a file

Video tutorial

Conclusion

We learnt all-important functionality of zip utility in this tutorial and hope provided examples are good enough to understand it.

if you still face any issue or want to explore more on zipping files in Linux or compress files in Unix, use «man zip» command or man page in Linux. Probably the best source of information.

Further reading recommendations:-

After this «How to zip a file in Linux» tutorial, Soon I will return with «unzip» post. Till that time, enjoy.

Please leave your comments or feedback. it will motivate to write more helpful posts.

Источники информации:

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

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