Zip linux archive folder

Содержание
  1. How to zip a folder in Ubuntu Linux / Debian Linux
  2. zip a folder in Ubuntu Linux using the cli
  3. How do I use zip command to compress a folder?
  4. Compress a directory in Ubuntu Linux
  5. zip a folder in Ubuntu Linux using the GUI method
  6. Password protecting zip file
  7. Conclusion
  8. Как заархивировать файлы и каталоги в Linux
  9. zip Команда
  10. Установите Zip в Ubuntu и Debian
  11. Установите Zip на CentOS и Fedora
  12. Как архивировать файлы и каталоги
  13. Методы и уровни сжатия
  14. Создание ZIP-файла, защищенного паролем
  15. Создание разделенного Zip-файла
  16. Примеры ZIP
  17. Выводы
  18. How to Zip Files and Folders in Linux [Beginner Tip]
  19. Zip a folder in Linux Command Line
  20. Zip a folder in Ubuntu Linux Using GUI
  21. Linux zip folder | 16 practical Linux zip command examples
  22. Linux Zip Command Examples
  23. Pre-requisite:
  24. Install zip
  25. Install unzip
  26. 1. How to zip a folder with multiple files Linux
  27. 2. How to create a zip file by excluding some files
  28. 3. How to zip a folder by compressing directory and sub-directories
  29. 4. How to display zip archive content
  30. 5. How to zip a folder with password protection
  31. 6. How to update or modify existing file in zip archive
  32. 7. How to add files to existing zip archive
  33. 8. How to list zip archive contents without extracting
  34. 9. How to create a zip file without complete path (Store only the file name)
  35. 10. How to create a zip file and delete original files after archiving
  36. 11. How to zip a folder with higher compression level
  37. 12. How to copy files between two zip archives
  38. 13. Linux zip directory and remove files from zip archive
  39. 14. Linux zip folder and preserve symbolic links
  40. Unzip to directory using unzip command
  41. 15. How to create a zip file and compress with bzip2
  42. Extract content using unzip command
  43. 16. How to zip a folder and later split zip archive
  44. References:
  45. Related Posts

How to zip a folder in Ubuntu Linux / Debian Linux

zip a folder in Ubuntu Linux using the cli

First install the zip command using apt command or apt-get command. Open the terminal and type the following command:
$ sudo apt install zip unzip

How do I use zip command to compress a folder?

The syntax is
zip -r filename.zip folder
zip -r filename.zip folder1 folder2
zip -r filename.zip /path/to/folder1 /path/to/file2
To create compressed archive named data.zip of data folder in the current directory, run:
zip -r data.zip data/

Verify file with the ls command:
ls -l data.zip
You can encrypt data.zip with a password by passing the -e option:
zip -r -e data.zip data/
Sample outputs:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

zip command has many more options as follows:

Option Description
-f freshen: only changed files
-u update: only changed or new files
-d delete entries in zipfile
-m move into zipfile (delete OS files)
-r recurse into directories
-j junk (don’t record) directory names
-0 store only
-l convert LF to CR LF (-ll CR LF to LF)
-1 compress faster
-9 compress better
-q quiet operation
-v verbose operation/print version info
-c add one-line comments
-z add zipfile comment
-@ read names from stdin
-o make zipfile as old as latest entry
-x exclude the following names
-i include only the following names
-F fix zipfile (-FF try harder)
-D do not add directory entries
-A adjust self-extracting exe
-J junk zipfile prefix (unzipsfx)
-T test zipfile integrity
-X eXclude eXtra file attributes
-y store symbolic links as the link instead of the referenced file
-e encrypt
-n don’t compress these suffixes
-h2 show more help

Compress a directory in Ubuntu Linux

The zip command syntax is as follows to compress a directory in Ubuntu Linux:
zip -r compressed_data.zip /path/to/foldername
zip -r compressed_data.zip /home/vivek/Jan-2018

zip a folder in Ubuntu Linux using the GUI method

To access and organize your files you use “Files” app (file manager)”. Use the Files file manager to browse and organize the files on your computer. Open it. Select folder name such as data and right click the “Compress…“:

Gif 01: Compressing a folder in Ubuntu Linux using GUI method i.e. Files file manager

Password protecting zip file

We can encrypt and password protect our zip file as follows:
zip -r -e output.zip /path/to/folder/
We can also use and state password on the CLI to encrypt zipfile entries:
zip -r -e -P ‘YOUR_PASSWORD_HERE’ output.zip /path/to/folder/

WARNING: The -P ‘YOUR_PASSWORD_HERE’ option to the zip IS INSECURE! Avoid it. Many multi-user operating systems such as Linux provide ways for any user to see the current command line of any other user; even on stand-alone systems there is always the threat of over-the-shoulder peeking. Storing the plaintext password as part of a command line in an automated script is even worse. Whenever possible, use the non-echoing, interactive prompt to enter passwords. And where security is truly important, use strong encryption such as Pretty Good Privacy (PGP/GPG) instead of the relatively weak standard encryption provided by zipfile utilities. See “ HowTo Encrypt And Decrypt Files With A Password Using GPG on Linux and Unix-like Systems” for more info.

Conclusion

You just learned how to compress a directory in Ubuntu Linux or Debian Linux using the zip command. The same command used to zip a folder in Linux. For more info please see this page here.

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Как заархивировать файлы и каталоги в Linux

Zip — это наиболее широко используемый формат архивных файлов, поддерживающий сжатие данных без потерь.

Zip-файл — это контейнер данных, содержащий один или несколько сжатых файлов или каталогов. Сжатые (заархивированные) файлы занимают меньше места на диске, их можно перенести с одного компьютера на другой быстрее, чем несжатые файлы. Zip-файлы можно легко извлечь в Windows, macOS и Linux с помощью утилит, доступных для всех операционных систем.

Читайте также:  Speedlink snappy microphone webcam 350k pixel драйвер windows 10

В этом руководстве мы покажем вам, как архивировать (сжимать) файлы и каталоги в Linux с помощью команды zip .

zip Команда

zip — это утилита командной строки, которая помогает создавать Zip-архивы.

Команда zip имеет следующий синтаксис:

Чтобы создать Zip-архив в определенном каталоге, пользователю необходимо иметь права на запись в этот каталог.

Zip-файлы не поддерживают информацию о владельце в стиле Linux. Извлеченные файлы принадлежат пользователю, выполняющему команду.

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

Утилита zip не устанавливается по умолчанию в большинстве дистрибутивов Linux, но вы можете легко установить ее с помощью диспетчера пакетов вашего дистрибутива.

Установите Zip в Ubuntu и Debian

Установите Zip на CentOS и Fedora

Как архивировать файлы и каталоги

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

По умолчанию команда zip печатает имена файлов, добавленных в архив, и метод сжатия. Мы объясним методы и уровень сжатия позже в этом руководстве.

При указании имени архива Zip, если вы опускаете расширение .zip оно будет добавлено автоматически, если имя архива не содержит точки. zip archivename.zip filename создаст архив с тем же именем, что и zip archivename filename .

Чтобы подавить вывод команды zip , используйте параметр -q :

Часто вы создаете Zip-архив каталога, включающего содержимое подкаталогов. Параметр -r позволяет рекурсивно просматривать всю структуру каталогов.

Чтобы создать Zip-архив каталога, вы должны использовать:

Вы также можете добавить несколько файлов и каталогов в один архив:

Методы и уровни сжатия

Метод сжатия Zip по умолчанию — deflate . Если утилита zip определяет, что файл нельзя сжать, она просто сохраняет файл в архиве, не сжимая его с помощью метода store . В большинстве дистрибутивов Linux утилита zip также поддерживает метод сжатия bzip2 .

Чтобы указать метод сжатия, используйте параметр -Z .

Команда zip позволяет указать уровень сжатия с помощью числа с префиксом от 0 до 9. Уровень сжатия по умолчанию -6 . При использовании -0 все файлы будут сохраняться без сжатия. -9 заставит команду zip использовать оптимальное сжатие для всех файлов.

Например, чтобы использовать уровень сжатия -9 , введите что-то вроде этого:

Чем выше уровень сжатия, тем интенсивнее процесс архивирования, и для его завершения потребуется больше времени.

Создание ZIP-файла, защищенного паролем

Если у вас есть конфиденциальная информация, которую необходимо сохранить в архиве, вы можете зашифровать ее с помощью параметра -e :

Вам будет предложено ввести и подтвердить пароль архива:

Создание разделенного Zip-файла

Представьте, что вы хотите сохранить Zip-архив на сервисе хостинга файлов, который имеет ограничение на размер загружаемого файла 1 ГБ, а ваш Zip-архив — 5 ГБ.

Вы можете создать новый разделенный Zip-файл, используя параметр -s с указанием размера. Множитель может быть k (килобайты), m (мегабайты), g (гигабайты) или t (терабайты).

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

Примеры ZIP

Создайте Zip-архив с именем archivename.zip, содержащий все файлы в текущем каталоге.

То же, что и выше, включая скрытые файлы (файлы, начинающиеся с точки):

Создайте Zip-архив с именем archivename.zip содержащий все файлы MP3 в текущем каталоге, без сжатия файлов.

Выводы

В Linux вы можете создавать Zip-архивы с помощью команды zip .

Чтобы распаковать ZIP-архив в системе Linux, вы можете использовать команду unzip .

Если вы хотите узнать больше о Zip, посетите страницу Zip Man .

Источник

How to Zip Files and Folders in Linux [Beginner Tip]

Last updated October 9, 2019 By Abhishek Prakash 30 Comments

Brief: This quick tip shows you how to create a zip folder in Ubuntu and other Linux distributions. Both terminal and GUI methods have been discussed.

Zip is one of the most popular archive file format out there. With zip, you can compress multiple files into one file. This not only saves disk space, it also saves network bandwidth. This is why you’ll encounter zip files almost all the time.

As a normal user, mostly you’ll unzip files in Linux. But how do you zip a folder in Linux? This article helps you answer that question.

Prerequisite: Verify if zip is installed

Normally zip support is installed but no harm in verifying. You can run the below command to install zip and unzip support. If it’s not installed already, it will be installed now.

Now that you know your system has zip support, you can read on to learn how to zip a directory in Linux.

Zip a folder in Linux Command Line

The syntax for using the zip command is pretty straight forward.

While there could be several options, I don’t want you to confuse with them. If your only aim is to create a zip folder from a bunch of files and directories, use the command like this:

The -r option will recurse into directories and compress its contents as well. The .zip extension in the output files is optional as .zip is added by default.

You should see the files being added to the compressed folder during the zip operation.

You are not always restricted to the terminal for creating zip archive files. You can do that graphically as well. Here’s how!

Zip a folder in Ubuntu Linux Using GUI

Though I have used Ubuntu here, the method should be pretty much the same in other distributions using GNOME or other desktop environment.

If you want to compress a file or folder in desktop Linux, it’s just a matter of a few clicks.

Go to the folder where you have the desired files (and folders) you want to compress into one zip folder.

In here, select the files and folders. Now, right click and select Compress. You can do the same for a single file as well.

Now you can create a compressed archive file in zip, tar xz or 7z format. In case you are wondering, all these three are various compression algorithms that you can use for compressing your files.

Give it the name you desire and click on Create.

It shouldn’t take long and you should see an archive file in the same directory.

Well, that’s it. You successfully created a zip folder in Linux.

I hope this quick little tip helped you with the zip files. Please feel free to share your suggestions.

Like what you read? Please share it with others.

Источник

Linux zip folder | 16 practical Linux zip command examples

Table of Contents

Читайте также:  Linux ip link down

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

Use -x or —exclude to zip all files except some files to exclude files from being compressed and archived in Linux or Unix

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

Similarly you can also zip all folders and exclude some directories using -r to zip directories

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?

Use -r or —recurse-paths to zip a folder in Linux or Unix and compress directory structure recursively using Linux zip command example:

4. How to display zip archive content

We can use -dc or —display-counts to display running zip file count of entries. Check below Linux zip command example to list zip archive content without extracting.

5. How to zip a folder with password protection

You can zip a folder and also password protect the zip file using -e or —encrypt . With this argument you create a zip file with an encrypted password. Let us use this Linux zip command example to understand this better:

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 use -f or —freshen to update or modify zip file content. With -f you replace (freshen) an existing entry in the zip archive only if it has been modified more recently than the version already in the zip file, unlike the update option (-u) this will not add files that are not already in the 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

How to add files to the existing zip archive, instead of creating a new zip archive. If this operation fails, zip attempts to restore the archive to its original state . If the restoration fails, the archive might become corrupted. This option is ignored when there’s no existing archive or when at least one zip archive member must be updated or deleted.

In my earlier Linux zip command example I had created a zip archive /tmp/test_archive.zip . Here we will will add new files to the same zip archive

8. How to list zip archive contents without extracting

You can also list zip archive contents without unzip to directory using -sf . For instance you have a requirement to check if a file exists in the archive so without unzip to directory you can list the zip file contents on the output and use additional regex and tools to grep the file you are looking for.

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:

Here list the content of test_archive , as you see the relative path is stored along with the filename

So to create a zip file in Linux without complete path and only store the filename in zip archive, we use -j or —junk-paths . This will create a zip archive without relative path of the files and store just the name of file (junk the path), and do not store directory names. For Example:

List and verify the zip archive content.

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

  • By default when you create a zip file, it leaves the original files and folders after creating archive,
  • But you can also make zip delete original files after archiving is complete.
  • Instead of copy, Move the specified files into the zip archive
  • Actually, this deletes the original target directories/files after making the specified zip archive.
  • If a directory becomes empty after removal of the files, the directory is also removed.
  • No deletions are done until zip has created the archive without error .

This is useful for conserving disk space, but is potentially dangerous so it is recommended to use it in combination with -T to test the archive before you make zip delete original files after archiving. In this we create a zip archive, and then delete the original files are we zip the folder.

Читайте также:  Linux не могу залогиниться

After you zip a folder, verify the content stored under /tmp/files . So as expected the original files are deleted from the source location after archiving.

Similarly to store the entire content of /tmp/files including the source directory use -r directive

As expected our source directory is also deleted after archiving

11. How to zip a folder with higher compression level

When we zip a folder, the default zip compression level is -6 . zip command supports compression level from 5 where 0 means no compression and -9 means highest (maximum) compression. We will perform basic compression and monitor the time difference

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

We increase the compression level to -9 and create a zip folder which is considered as the highest or maximum compression level.

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

You can also copy files from one zip archive to another using -U or —copy-entries argument without extracting.

Also requires the —out option to specify a different output file than the input archive.

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

If no input files appear on the command line and —out is used, copy mode is assumed:

13. Linux zip directory and remove files from zip archive

In Linux zip directory and using -d or —delete directive you can delete or remove files from zip archive.

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

So to remove files from zip archive , I will remove two files from the existing zip archive without unzip to directory

Verify the content of the archive

14. Linux zip folder and preserve symbolic links

For UNIX and VMS (V8.3 and later) use -y or —symlinks , create a zip folder and store and preserve symbolic links in zip archive.

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

Next create a zip folder including symlink using -y or —symlinks argument to make zip preserve symbolic links

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

So with -y we make zip preserve symbolic links

Next verify the symlink content.

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

You can create a zip file with bzip2 compression. Set the default compression method using -Z or —compression-method . Currently the main methods supported by zip are store and deflate. Compression method can be set to:

  • store — Setting the compression method to store forces zip to store entries with no compression. This is generally faster than compressing entries, but results in no space savings. This is the same as using -0 (compression level zero).
  • deflate — This is the default method for zip. If zip determines that storing is better than deflation, the entry will be stored instead.
  • bzip2 — If bzip2 support is compiled in, this compression method also becomes available.

Extract content using unzip command

Extract the content using unzip to directory

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

  • How to zip a folder and enable creating a split zip archive and set the split size using -s or —split-size .
  • A split zip archive in Linux and Unix is an archive that could be split over many files.
  • As the zip archive is created, if the size of the archive reaches the specified split size, that split is closed and the next split opened.
  • In general all splits but the last will be the split size and the last will be whatever is left .
  • If the entire archive is smaller than the split size a single-file archive is created.
  • Split size is a number optionally followed by a multiplier.
  • Currently the number must be an integer.
  • The multiplier can currently be one of k (kilobytes), m (megabytes), g (gigabytes), or t (terabytes).
  • As 64k is the minimum split size, numbers without multipliers default to megabytes

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:

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.

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

Thank You for your support!!

Источник

Оцените статью