- Примеры использования zip и unzip в linux
- Установка zip и unzip:
- Пример использования утилиты zip
- How to unzip a zip file using the Linux and Unix bash shell terminal
- Use unzip command to unzip a zip file
- A note about bash: unzip: command not found
- Installing unzip on Debian/Ubuntu Linux
- Install unzip on Arch Linux
- CentOS/RHEL/Scientific/Oracle Linux install unzip command
- Fedora Linux install unzip
- Installing unzip on Suse/OpenSUSE Linux
- FreeBSD Unix install unzip
- OpenBSD Unix install unzip
- macOS Unix install unzip CLI
- Use tar command to unzip a zip file
- Linux unzip command
- Description
- Syntax
- Arguments
- Options
- Modifiers
- Options
- Decryption
- Examples
- Related commands
Примеры использования zip и unzip в linux
Сегодня я хотел сделать пост памятку по работе в Unix подобных системах с утилитами zip и unzip. Также рассмотреть несколько интересных команд, которые могут пригодиться для работы.
Установка zip и unzip:
В системе Debian/Ubuntu.
В системе Red Hat Linux/Fedora/CentOS.
Пример использования утилиты zip
Пример 1: Создания архива из указанных файлов и папок
Пример 2: Создания архива текущего каталога (архив создается без подкаталогов)
Пример 3: Создания архива включая все подкаталоги используем ключ -r
Создает архив без скрытых файлов/каталог это файлы/каталоги начинающиеся с .
Создает архив с скрытыми файлами и каталогами
Пример 4: Чтобы сжать быстро используйте -1, но для более лучшего сжатие используйте -9
Пример 5: Опция -x позволяет исключать файлы и каталоги из архива
Пример 6: Также опция -x позволяет исключать файлы и каталоги по шаблону
Таким способом я исключаю все каталоги заканчивающихся на ted и файлы расширения xml
Пример 7: Разбиваем архив на части с помощью опции -s
Также есть возможность указать опцию размера части архива в: k (KB), m (MB), g (GB), t (TB)
Пример 8: Задать пароль можно опцией -e или опцией -P .
Пример 9: Выбрать только указанные файлы/каталоги
Пример 10: Удаление файлов из созданного архива
Пример 11: Обновить содержимое созданного архива
Пример 11: Тихий режим (Полезно, например, в сценариях оболочки и фоновых задач)
Пример 12: Извлечь все содержимое архива
Пример 13: Извлечь все содержимое архива в указанную директорию
Пример 14: Показать содержимое архива
Пример 15: Извлечь конкретный файл из архива
Источник
How to unzip a zip file using the Linux and Unix bash shell terminal
Use unzip command to unzip a zip file
The syntax is:
unzip
Use the following syntax if you want to extract/unzip to a particular destination directory:
unzip -d /dest/directory/
For example, unzip a zip file named master.zip using zip command:
unzip master.zip
To unzip a zip file named master.zip using zip command to a /tmp/data/ directory:
unzip -d /tmp/data/ master.zip
Sample session:
Fig.02: How to unzip a zip file from the Terminal using unzip command
A note about bash: unzip: command not found
If the unzip command NOT installed on your Linux or Unix box, then run any one of the following commands as per your Linux distribution to install the unzip command.
Make sure you run the following command as the root user. For instance:
sudo command
OR
su —
Installing unzip on Debian/Ubuntu Linux
Use the apt-get command or apt command to install unzip command:
sudo apt-get install unzip
OR
sudo apt install unzip
Install unzip on Arch Linux
Use the pacman command to install unzip command:
pacman -S unzip
CentOS/RHEL/Scientific/Oracle Linux install unzip command
Use the yum command or dnf command to install unzip command:
yum install unzip
- 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 ➔
Fedora Linux install unzip
Use the dnf command to install unzip command:
dnf install unzip
Installing unzip on Suse/OpenSUSE Linux
Use the zypper command to install unzip command:
zypper install unzip
FreeBSD Unix install unzip
To install the unzip port, run:
# cd /usr/ports/archivers/unzip/ && make install clean
To add the package rung pkg command:
# pkg install unzip
OpenBSD Unix install unzip
macOS Unix install unzip CLI
Let us install Homebrew on macOS. Once installed type the following brew command to install unzip utility:
$ brew install unzip
Use tar command to unzip a zip file
The syntax is:
tar xvf
tar -xvf
Use the following syntax if you want to extract/unzip to a particular destination directory:
tar xvf
tar -xvf
For example, unzip a zip file named master.zip using tar command:
tar xvf master.zip
To unzip a zip file named master.zip using tar command to a /tmp/data/ directory:
tar xvf master.zip -C /tmp/data/
ls -l /tmp/data/
cd /tmp/data/
ls -l
Sample session:
Fig.01: How to use a tar command to unzip a file on Linux/Unix-like terminal
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
I’d just like to interject for a moment. What you’re referring to as Linux, is in fact, GNU/Linux, or as I’ve recently taken to calling it, GNU plus Linux. Linux is not an operating system unto itself, but rather another free component of a fully functioning GNU system made useful by the GNU corelibs, shell utilities and vital system components comprising a full OS as defined by POSIX.
Many computer users run a modified version of the GNU system every day, without realizing it. Through a peculiar turn of events, the version of GNU which is widely used today is often called “Linux”, and many of its users are not aware that it is basically the GNU system, developed by the GNU Project.
There really is a Linux, and these people are using it, but it is just a part of the system they use. Linux is the kernel: the program in the system that allocates the machine’s resources to the other programs that you run. The kernel is an essential part of an operating system, but useless by itself; it can only function in the context of a complete operating system. Linux is normally used in combination with the GNU operating system: the whole system is basically GNU with Linux added, or GNU/Linux. All the so-called “Linux” distributions are really distributions of GNU/Linux.
unzip worked for a zip file, tar xvf did not work for me…
error:
tar: This does not look like a tar archive
tar: Skipping to next header
tar: Exiting with failure status due to previous errors
You cannot use tar to extract a zip file. I demand that you fix this web page.
Источник
Linux unzip command
On Unix-like operating systems, the unzip command lists, extracts, and tests compressed files in a ZIP archive.
This page covers the Linux version of unzip.
Description
unzip lists, tests, or extracts files from archives of the zip format, which are most commonly found on MS-DOS and Windows systems. The default behavior (with no options) is to extract into the current directory (and possibly the subdirectories below it) all files from the specified zip archive. A companion program, zip, creates zip archives. Both zip and unzip are compatible with archives created by PKWARE’s PKZIP and PKUNZIP programs for MS-DOS.
Syntax
Arguments
unzip accepts the following arguments:
file[.zip] | Path of the zip archive(s). If the file specification is a wildcard, each matching file is processed in an order determined by the operating system (or file system). Only the filename can be a wildcard; the path itself cannot. Wildcard expressions are similar to those supported in commonly used Unix shells (sh, ksh, csh) and may contain:
(Be sure to quote any character that might otherwise be interpreted or modified by the operating system, particularly under Unix and VMS.) If no matches are found, the specification is assumed to be a literal filename; and if that also fails, the suffix .zip is appended. Note that self-extracting zip files are supported, as with any other zip archive; just specify the .exe suffix (if any) explicitly. | ||||||
[file(s)] | An optional list of archive members to be processed, separated by spaces. (VMS versions compiled with VMSCLI defined must delimit files with commas instead. See -v in OPTIONS below.) Regular expressions (wildcards) may be used to match multiple members, as stated above. Again, be sure to quote expressions that would otherwise be expanded or modified by the operating system. | ||||||
[-x xfile(s)] | An optional list of archive members to be excluded from processing. Since wildcard characters normally match (‘/‘) directory separators (for exceptions see the option -W), this option may be used to exclude any files that are in subdirectories. For example, «unzip foo *.[ch] -x */*» would extract all C source files in the main directory, but none in any subdirectories. Without the -x option, all C source files in all directories within the zipfile would be extracted. | ||||||
[-d exdir] | If specified, files will be extracted to directory exdir. By default, all files and subdirectories are recreated in the current directory; the -d option allows extraction in an arbitrary directory (always assuming one has permission to write to the directory). This option need not appear at the end of the command line; it is also accepted before the zipfile specification (with the normal options), immediately after the zipfile specification, or between the file(s) and the -x option. The option and directory may be concatenated without any white space between them, but note that this may cause normal shell behavior to be suppressed. In particular, «-d » (tilde) is expanded by Unix C shells into the name of the user’s home directory, but «-d » of the current directory. |
Options
Additionally, unzip accepts the following options:
-Z | zipinfo mode. If the first option on the command line is -Z, the remaining options are taken to be zipinfo options. |
-A | [OS/2, Unix DLL] print extended help for the DLL’s programming interface (API). |
-c | extract files to stdout/screen («the CRT»). This option is similar to the -p option except that the name of each file is printed as it is extracted, the -a option is allowed, and ASCII-EBCDIC conversion is automatically performed if appropriate. This option is not listed in the unzip usage screen. |
-f | freshen existing files, i.e., extract only those files that already exist on disk and that are newer than the disk copies. By default, unzip queries before overwriting, but the -o option may be used to suppress the queries. Note that under many operating systems, the TZ (timezone) environment variable must be set correctly for -f and -u to work properly (under Unix the variable is usually set automatically). The reasons for this are somewhat subtle but have to do with the differences between DOS-format file times (always local time) and Unix-format times (always in GMT/UTC) and the necessity to compare the two. A typical TZ value is «PST8PDT» (US Pacific time with automatic adjustment for Daylight Savings Time). |
-l | list archive files (short format). The names, uncompressed file sizes and modification dates and times of the specified files are printed, along with totals for all files specified. If unzip was compiled with OS2_EAS defined, the -l option also lists columns for the sizes of stored OS/2 extended attributes (EAs) and OS/2 access control lists (ACLs). Also, the zipfile comment and individual file comments (if any) are displayed. If a file was archived from a single-case file system (for example, the old MS-DOS FAT file system) and the -L option was given, the filename is converted to lowercase and is prefixed with a caret (^). |
-p | extract files to pipe (standard output, stdout). Nothing but the file data is sent to stdout, and the files are always extracted in binary format, just as they are stored (no conversions). |
-t | test archive files. This option extracts each specified file in memory and compares the CRC (cyclic redundancy check, an enhanced checksum) of the expanded file with the original file’s stored CRC value. |
-T | [most OSes] set the timestamp on the archive(s) to that of the newest file in each one. This corresponds to zip’s -go option except that it can be used on wildcard zipfiles (e.g., «unzip -T \*.zip«) and is much faster. |
-u | update existing files and create new ones if needed. This option performs the same function as the -f option, extracting (with query) files that are newer than those with the same name on disk, and in addition it extracts those files that do not already exist on disk. See -f above for information on setting the timezone properly. |
-v | list archive files (verbose format) or show diagnostic version info. This option has evolved and now behaves as both an option and a modifier. As an option it has two purposes: when a zipfile is specified with no other options, -v lists archive files verbosely, adding to the basic -l info the compression method, compressed size, compression ratio and 32-bit CRC. In contrast to most of the competing utilities, unzip removes the 12 additional header bytes of encrypted entries from the compressed size numbers. Therefore, compressed size and compression ratio figures are independent of the entry’s encryption status and show the correct compression performance. (The complete size of the encrypted compressed data stream for zipfile entries is reported by the more verbose zipinfo reports.) When no zipfile is specified (that is, the complete command is «unzip -v«), a diagnostic screen is printed. In addition to the normal header with release date and version, unzip lists the home Info-ZIP ftp site and where to find a list of other ftp and non-ftp sites; the target operating system for which it was compiled, as well as (possibly) the hardware on which it was compiled, the compiler and version used, and the compilation date; any special compilation options that might affect the program’s operation (see also DECRYPTION below); and any options stored in environment variables that might do the same (see ENVIRONMENT OPTIONS below). As a modifier it works in conjunction with other options (e.g., -t) to produce more verbose or debugging output. |
-z | display only the archive comment. |
Modifiers
-a | convert text files. Ordinarily all files are extracted exactly as they are stored (as «binary» files). The -a option causes files identified by zip as text files (those with the ‘t‘ label in zipinfo listings, rather than ‘b‘) to be automatically extracted as such, converting line endings, end-of-file characters and the character set itself as necessary. (For example, Unix files use line feeds (LFs) for end-of-line (EOL) and have no end-of-file (EOF) marker; Macintoshes use carriage returns (CRs) for EOLs; and most PC operating systems use CR+LF for EOLs and control-Z for EOF. Also, IBM mainframes and the Michigan Terminal System use EBCDIC rather than the more common ASCII character set, and NT supports Unicode.) Note that zip‘s identification of text files is by no means perfect; some «text» files may actually be binary and vice versa. unzip therefore prints «[text]» or «[binary]» as a visual check for each file it extracts when using the -a option. The -aa option forces all files to be extracted as text, regardless of the supposed file type. On VMS, see also -S |
-b | [general] treat all files as binary (no text conversions). This is a shortcut for —a. |
-b | [Tandem] force the creation files with file code type 180 (‘C‘) when extracting Zip entries marked as «text». (On Tandem, -a is enabled by default; see above). |
-b | [VMS] auto-convert binary files (see -a above) to fixed-length, 512-byte record format. Doubling the option (-bb) forces all files to be extracted in this format. When extracting to standard output (-c or -p option in effect), the default conversion of text record delimiters is disabled for binary (-b) resp. all (-bb) files. |
-B | [when compiled with UNIXBACKUP defined] save a backup copy of each overwritten file. The backup file is gets the name of the target file with a tilde and optionally a unique sequence number (up to 5 digits) appended. The sequence number is applied whenever another file with the original name plus tilde already exists. When used together with the «overwrite all» option -o, numbered backup files are never created. In this case, all backup files are named as the original file with an appended tilde, existing backup files are deleted without notice. This feature works similarly to the default behavior of emacs in many locations. |
As an example, an old copy of «foo» is renamed to «foo
Warning: Users should be aware that the -B option does not prevent loss of existing data under all circumstances. For example, when unzip is run in overwrite-all mode, an existing «foo
» file is deleted before unzip attempts to rename «foo» to «foo
«. When this rename attempt fails (because of a file locks, insufficient privileges, or whatever), the extraction of «foo
» gets cancelled, but the old backup file is already lost. A similar scenario takes place when the sequence number range for numbered backup files gets exhausted (99999, or 65535 for 16-bit systems). In this case, the backup file with the maximum sequence number is deleted and replaced by the new backup version without notice.
Please note that the -C option does neither affect the search for the zipfile(s) nor the matching of archive entries to existing files on the extraction path. On a case-sensitive file system, unzip will never try to overwrite a file «FOO» when extracting an entry «foo«!
On VMS, the default setting for this option is -D for consistency with the behaviour of BACKUP: file timestamps are restored, timestamps of extracted directories are left at the current time. To enable restoration of directory timestamps, the negated option —D should be specified. On VMS, the option -D disables timestamp restoration for all extracted Zip archive items. (Here, a single -D on the command line combines with the default -D to do what an explicit -DD does on other systems.)
The option -UU allows to entirely disable the recognition of UTF-8 encoded filenames. The handling of filename codings within unzip falls back to the behaviour of previous versions.
[old, obsolete usage] leave filenames uppercase if created under MS-DOS, VMS, etc. See -L above.
- «*.c» matches «foo.c» but not «mydir/foo.c«
- «**.c» matches both «foo.c» and «mydir/foo.c«
- «*/*.c» matches «bar/foo.c» but not «baz/bar/foo.c«
- «??*/*» matches «ab/foo» and «abc/foo» but not «a/foo» or «a/b/foo«
This modified behaviour is equivalent to the pattern matching style used by the shells of some of UnZip’s supported target OSs (one example is Acorn RISC OS). This option may not be available on systems where the Zip archive’s internal directory separator character ‘/‘ is allowed as regular character in native operating system filenames. (Currently, unzip uses the same pattern matching rules for both wildcard zipfile specifications and zip entry selection patterns in most ports. For systems allowing `/‘ as regular filename character, the -W option would not work as expected on a wildcard zipfile specification.)
Options
unzip‘s default behavior may be modified via options placed in an environment variable. This can be done with any option, but it is probably most useful with the -a, -L, -C, -q, -o, or -n modifiers: make unzip auto-convert text files by default, make it convert filenames from uppercase systems to lowercase, make it match names case-insensitively, make it quieter, or make it always overwrite or never overwrite files as it extracts them. For example, to make unzip act as quietly as possible, only reporting errors, one would use one of the following commands:
VMS (quotes for lowercase):
Environment options are, in effect, considered to be just like any other command-line options, except that they are effectively the first options on the command line. To override an environment option, one may use the «minus operator» to remove it. For instance, to override one of the quiet-flags in the example above, use the command below.
The first hyphen is the normal switch character, and the second is a minus sign, acting on the q option. Thus the effect here is to cancel one quantum of quietness. To cancel both quiet flags, two (or more) minuses may be used:
(the two are equivalent). This may seem awkward or confusing, but it is reasonably intuitive: just ignore the first hyphen and go from there. It is also consistent with the behavior of Unix nice.
As suggested by the examples above, the default variable names are UNZIP_OPTS for VMS (where the symbol used to install unzip as a foreign command would otherwise be confused with the environment variable), and UNZIP for all other operating systems. For compatibility with zip, UNZIPOPT is also accepted. If both UNZIP and UNZIPOPT are defined, however, UNZIP takes precedence. unzip‘s diagnostic option (-v with no zipfile name) can be used to check the values of all four possible unzip and zipinfo environment variables.
The timezone variable (TZ) should be set according to the local timezone for the -f and -u to operate correctly. See the description of -f above for details. This variable may also be necessary to get timestamps of extracted files to be set correctly. The WIN32 (Win9x/ME/NT4/2K/XP/2K3) port of unzip gets the timezone configuration from the Registry, assuming it is correctly set in the Control Panel. The TZ variable is ignored for this port.
Decryption
Encrypted archives are fully supported by Info-ZIP software, but due to United States export restrictions, de-/encryption support might be disabled in your particular compiled binary. However, since the spring of 2000, US export restrictions have been liberated, and our source archives do now include full crypt code. In case you need binary distributions with crypt support enabled, see the file «WHERE» in any Info-ZIP source or binary distribution for locations both inside and outside the US.
Some compiled versions of unzip may not support decryption. To check a version for crypt support, either attempt to test or extract an encrypted archive, or else check unzip‘s diagnostic screen (see the -v option above) for «[decryption]» as one of the special compilation options.
As noted above, the -P option may be used to supply a password on the command line, but at a cost in security. The preferred decryption method is to extract normally; if a zipfile member is encrypted, unzip will prompt for the password without echoing what is typed. unzip continues to use the same password as long as it appears to be valid, by testing a 12-byte header on each file. The correct password will always check out against the header, but there is a 1-in-256 chance that an incorrect password will as well. (This is a security feature of the PKWARE zipfile format; it helps prevent brute-force attacks that might otherwise gain a large speed advantage by testing only the header.) In the case that an incorrect password is given but it passes the header test anyway, either an incorrect CRC will be generated for the extracted data or else unzip will fail during the extraction because the «decrypted» bytes do not constitute a valid compressed data stream.
If the first password fails the header check on some file, unzip will prompt for another password, and so on until all files are extracted. If a password is not known, entering a null password (that is, just a carriage return or «Enter») is taken as a signal to skip all further prompting. Only unencrypted files in the archive(s) will thereafter be extracted. (In fact, that’s not quite true; older versions of zip and zipcloak allowed null passwords, so unzip checks each encrypted file to see if the null password works. This may result in «false positives» and extraction errors, as noted above.)
Archives encrypted with 8-bit passwords (for example, passwords with accented European characters) may not be portable across systems and/or other archivers. This problem stems from the use of multiple encoding methods for such characters, including Latin-1 (ISO 8859-1) and OEM code page 850. DOS PKZIP 2.04g uses the OEM code page; Windows PKZIP 2.50 uses Latin-1 (and is therefore incompatible with DOS PKZIP); Info-ZIP uses the OEM code page on DOS, OS/2 and Win3.x ports but ISO coding (Latin-1 etc.) everywhere else; and Nico Mak’s WinZip 6.x does not allow 8-bit passwords at all. unzip 5.3 (or newer) attempts to use the default character set first (e.g., Latin-1), followed by the alternate one (e.g., OEM code page) to test passwords. On EBCDIC systems, if both of these fail, EBCDIC encoding will be tested as a last resort. (EBCDIC is not tested on non-EBCDIC systems, because there are no known archivers that encrypt using EBCDIC encoding.) ISO character encodings other than Latin-1 are not supported. The new addition of (partially) Unicode (resp. UTF-8) support in UnZip 6.0 has not yet been adapted to the encryption password handling in unzip. On systems that use UTF-8 as native character encoding, unzip tries decryption with the native UTF-8 encoded password; the built-in attempts to check the password in translated encoding have not yet been adapted for UTF-8 support and will consequently fail.
Examples
Unzip the hope.zip archive into the current directory, creating subdirectories as needed to match the archive’s file hierarchy.
Extract the files from archive hope.zip into the current directory only, regardless of the archive’s internal directory structure.
Test hope.zip for errors, but do not extract anything. The q indicates «quiet» mode, which instructs unzip to return only a summary message, rather than a more detailed one.
Display the contents of all files with the extension .txt contained in the archive hope.zip to the standard output.
Extract from the hope.zip archive any C source files with the extensions .c and .h, and any files named Makefile, into the directory /tmp.
Same as the above command, but case-insensitive; it will also extract any files with the extensions .C or .H, any files named MAKEFILE, any files named MakeFile, etc.
Extract files from the archive hope.zip, but only if they are newer versions than the files that already exist.
Display a listing of the contents of hope.zip without extracting anything.
Related commands
gzip — Create, modify, list the contents of, and extract files from GNU zip archives.
zip — A compression and archiving utility.
zipinfo — Display technical information about a zip file.
Источник