fbpx

Comandos Linux – Comando zip

Comando zip do Linux

comando zip

O programa zip é usado para compactar e compactar arquivos.

Descrição

zip é um utilitário de compactação e empacotamento de arquivos para Unix , VMS , MSDOS , OS / 2 , Windows 9x / NT / XP , Minix , Atari , Macintosh , Amiga e Acorn RISC OS . É análogo a uma combinação dos comandos do Unix tar e compress , e é compatível com o PKZIP .

Um programa complementar separado, descompacta , descompacta e descompacta arquivos zip . Os programas zip e descompacte podem funcionar com arquivos produzidos pelo PKZIP (suportando a maioria dos recursos do PKZIP até o PKZIP versão 4.6), e o PKZIP e o PKUNZIP podem trabalhar com arquivos produzidos pelo zip (com algumas exceções).

O zip suporta o macOS X e, nesse SO, a maioria dos recursos do Unix são os mesmos.

Uso

zip é útil para empacotar um conjunto de arquivos para distribuição, arquivar arquivos e economizar espaço em disco compactando temporariamente arquivos ou diretórios não utilizados .

O programa zip coloca um ou mais arquivos compactados em um único arquivo zip , junto com informações sobre os arquivos (nome, caminho, data, hora da última modificação, proteção e informações de verificação para verificar a integridade do arquivo ). Uma estrutura de diretórios inteira pode ser compactada em um arquivo zip com um único comando. As taxas de compressão de 2: 1 a 3: 1 são comuns para arquivos de texto. O zip possui um método de compactação ( deflação ) e também pode armazenar arquivos sem compactação. (Se o suporte ao bzip2 for adicionado, o zip também poderá compactar usando a compactação do bzip2 , mas essas entradas exigirão um descompacte razoavelmente modernodescomprimir. Quando a compactação bzip2 é selecionada, ela substitui a deflação como o método padrão.) Zip escolhe automaticamente o melhor dos dois ( deflação ou armazenamento ou, se bzip2 estiver selecionado, bzip2 ou armazenamento ) para cada arquivo a ser compactado.

Formato de comando

O formato básico do comando é:

arquivo de opções zip arquivo inpath ...

… em que archive é um arquivo zip novo ou existente e inpath é um diretório ou caminho de arquivo opcionalmente incluindo curingas. Quando recebe o nome de um arquivo zip existente, o zip substitui entradas nomeadas de forma idêntica no arquivo zip (correspondendo aos nomes relativos armazenados no arquivo morto) ou adiciona entradas para novos nomes. Por exemplo, se foo.zip existir e contiver foo / file1 e foo / file2 , e o diretório foo contiver os arquivos foo / file1 e foo / file3 , então:

zip -r foo.zip foo

ou mais concisamente:

zip -r foo foo

… substituirá foo / file1 em foo.zip e adicionará foo / file3 a foo.zip . Depois disso, foo.zip contém foo / file1 , foo / file2 e foo / file3 , com foo / file2 inalterado antes.

Portanto, se antes do comando zip ser executado, foo.zip possui:

foo / file1 
foo / file2

e o diretório foo tem:

file1 
arquivo3

então foo.zip terá:

foo / file1 
foo / file2 
foo / file3

… onde foo / file1 é substituído e foo / file3 é novo.

Listas de arquivos

Se uma lista de arquivos for especificada como – @ , zip utilizará a lista de arquivos de entrada da entrada padrão em vez da linha de comando. Por exemplo,

zip - @ foo

… armazenará os arquivos listados, um por linha na entrada padrão, no arquivo foo.zip .

No Unix, esta opção pode ser usada com efeitos poderosos em conjunto com o comando find . Por exemplo, para arquivar todos os arquivos de origem C no diretório atual e seus subdiretórios:

encontrar . -name "*. [ch]" -print | fonte zip - @

(observe que o padrão deve ser citado para impedir que o shell o expanda).

Streaming de entrada e saída. O zip também aceitará um único traço (”  “) como o nome do arquivo zip ; nesse caso, ele gravará o arquivo zip na saída padrão, permitindo que a saída seja canalizada para outro programa. Por exemplo:

zip -r -. | dd de = / dev / nrst0 obs = 16k

… gravaria a saída zip diretamente em uma fita com o tamanho de bloco especificado com o objetivo de fazer backup do diretório atual.

zip também aceita um único traço (”  “) como o nome de um arquivo a ser compactado; nesse caso, ele lerá o arquivo da entrada padrão, permitindo que o zip receba a entrada de outro programa. Por exemplo:

tar cf -. | backup zip -

…would compress the output of the tar command for the purpose of backing up the current directory. This generally produces better compression than the previous example using the -r option because zip can take advantage of redundancy between files. The backup can be restored using the command:

unzip -p backup | tar xf -

When no zip file name is given and stdout is not a terminal, zip acts as a filter, compressing standard input to standard output. For example,

tar cf - . | zip | dd of=/dev/nrst0 obs=16k

…is equivalent to

tar cf - . | zip - - | dd of=/dev/nrst0 obs=16k

zip archives created in this manner can be extracted with the program funzip that is provided in the unzip package, or by gunzip that is provided in the gzip package (but some installations of gunzip may not support this if zip used the Zip64 extensions). For example:

dd if=/dev/nrst0 ibs=16k | funzip | tar xvf -

The stream can also be saved to a file and unzip used.

If Zip64 support for large files and archives is enabled and zip is used as a filter, zip creates a Zip64 archive that requires a PKZIP 4.5 or later compatible unzip to read the file. To avoid amgibuities in the zip file structure as defined in the current zip standard (PKWARE AppNote) where the decision to use Zip64 needs to be made before data is written for the entry, but for a stream the size of the data is not known at that point. If the data is known to be smaller than 4 GB, the option -fz- can be used to prevent use of Zip64, but zip will exit with an error if Zip64 was in fact needed. zip 3 and unzip 6 and later can read archives with Zip64 entries. Also, zip removes the Zip64 extensions if not needed when archive entries are copied (see the -U (–copy) option).

When directing the output to another file, note that all options should be before the redirection including -x. For example:

zip archive "*.h" "*.c" -x donotinclude.h orthis.h > tofile

Please note that -@ lists do not work on macOS.

Zip Files

When changing an existing zip archive, zip will write a temporary file with the new contents, and only replace the old one when the process of creating the new version has been completed without error.

If the name of the zip archive does not contain an extension, the extension .zip is added. If the name already contains an extension other than .zip, the existing extension is kept unchanged. However, split archives (archives split over multiple files) require the .zip extension on the last split.

Scanning And Reading Files

Quando o zip é iniciado, ele verifica os arquivos a serem processados ​​(se necessário). Se essa verificação demorar mais de 5 segundos, o zip exibirá a mensagem “Verificando arquivos” e comece a exibir pontos de progresso a cada 2 segundos ou a cada uma das entradas processadas, o que levar mais tempo. Se houver mais de 2 segundos entre os pontos, isso pode indicar que a localização de cada arquivo está demorando e pode significar uma conexão de rede lenta, por exemplo. (Na verdade, a verificação inicial do arquivo é um processo de duas etapas, em que a verificação do diretório é seguida por uma classificação e essas duas etapas são separadas por um espaço nos pontos. Se você estiver atualizando um arquivo morto existente, também aparecerá um espaço entre a verificação do arquivo existente e a nova verificação de arquivos.) os pontos varredura de arquivos não são controlados pelas -dsopção de tamanho de ponto, mas os pontos são desativados pela opção -q quiet. A opção -sf show files pode ser usada para verificar arquivos e obter a lista de arquivos verificados sem processá-los.

Se o zip não puder ler um arquivo, ele emitirá um aviso, mas continuará. Consulte a opção -MM abaixo para obter mais informações sobre como o zip lida com padrões que não correspondem e arquivos que não são legíveis. Se alguns arquivos foram ignorados, um aviso é emitido no final da operação zip, indicando quantos arquivos foram lidos e quantos foram ignorados.

Modos de comando

O zip agora suporta dois tipos distintos de modos de comando, externo e interno. Os modos externos ( adicionar , atualização , e refrescar ) ler arquivos do sistema de arquivos (assim como a partir de um arquivo existente), enquanto os modos internos ( apagar e copiar ) a operar exclusivamente em entradas em um arquivo existente.

Adicionar, acrescentarAtualize as entradas existentes, adicione novos arquivos e crie-os se o arquivo morto não existir. Esta opção é o modo padrão.
atualização ( -u )Atualize as entradas existentes, se mais novas, no sistema de arquivos e adicione novos arquivos. Se o arquivo não existir, emitir um aviso, crie um novo arquivo.
refrescar ( -f )Atualize as entradas existentes de um archive, se mais recente no sistema de arquivos. Não adiciona novos arquivos ao arquivo morto.
excluir ( -d )Selecione as entradas em um arquivo existente e exclua-as.
cópia ( -U )Selecione as entradas em um arquivo existente e copie-as para um novo arquivo. Esse novo modo é semelhante à atualização, mas os padrões de linha de comando selecionam entradas no arquivo morto existente, em vez de arquivos do sistema de arquivos, e usa a opção –out para gravar o arquivo resultante em um novo arquivo, em vez de atualizar o arquivo existente, deixando o arquivo original inalterado.

A nova opção de sincronização de arquivos ( -FS ) também é considerada um novo modo, embora seja semelhante à atualização. Esse modo sincroniza o arquivo morto com os arquivos no sistema operacional, substituindo apenas os arquivos no arquivo se a hora ou o tamanho do arquivo for diferente, adicionando novos arquivos e excluindo entradas do arquivo onde não há arquivo correspondente. Como esse modo pode excluir entradas do arquivo morto, considere fazer uma cópia de backup do arquivo morto.

Veja também -DF para criar arquivos de diferença.

Arquivos divididos

O zip versão 3.0 e posterior pode criar arquivos divididos. Um arquivo dividido é um arquivo zip padrão dividido em vários arquivos. (Observe que os arquivos divididos não são apenas arquivos divididos em partes, pois as compensações das entradas agora são baseadas no início de cada divisão. Concatenar as partes juntas invalidará essas compensações, mas o descompactamento geralmente pode lidar com isso. Zip geralmente recusará. para processar um arquivamento emendado, a menos que a opção de correção -FF seja usada para corrigir os desvios.)

Um uso de arquivos divididos é armazenar um arquivo grande em várias mídias removíveis. Para um arquivo dividido com 20 arquivos separados, os arquivos geralmente são nomeados (substitua ARQUIVO pelo nome do seu arquivo) ARCHIVE.z01 , ARCHIVE.z02 , …, ARCHIVE.z19 , ARCHIVE.zip . Observe que o último arquivo é o arquivo .zip . Por outro lado, os arquivos estendidos são o arquivo múltiplo original, geralmente exigindo disquetes e usando rótulos de volume para armazenar números de disco. fecho eclairsuporta arquivos divididos, mas não arquivos estendidos, embora exista um procedimento para converter arquivos divididos do tamanho certo em arquivos estendidos. O inverso também é verdadeiro, onde cada arquivo de um archive estendido pode ser copiado para arquivos com os nomes acima para criar um archive dividido.

Use -s para definir o tamanho da divisão e criar um arquivo dividido. O tamanho é dado como um número seguido opcionalmente por um de k (kB), m (MB), g (GB) ou t (TB) (o padrão é m ). A opção -sp pode ser usada para pausar o zip entre as divisões para permitir a troca de mídia removível, por exemplo, mas leia as descrições e os avisos para ambos -s e -sp abaixo.

Embora o zip não atualize os arquivos divididos, o zip fornece a nova opção -O ( –output-file ou –out ) para permitir que os arquivos divididos sejam atualizados e salvos em um novo arquivo morto . Por exemplo,

zip inarchive.zip foo.c bar.c --out outarchive.zip

… lê o arquivo inarchive.zip , mesmo que dividido, adiciona os arquivos foo.c e bar.c e grava o arquivo resultante em outarchive.zip . Se inarchive.zip estiver dividido, outarchive.zip assumirá o mesmo tamanho de divisão. Esteja ciente de que se outarchive.zip e quaisquer arquivos divididos criados com ele já existirem, eles sempre serão substituídos conforme necessário, sem aviso. Isso pode ser alterado no futuro.

Suporte Unicode

Though the zip standard requires storing paths in an archive using a specific character set, in practice zips have stored paths in archives in whatever the local character set is. Problems can occur when an archive is created or updated on a system using one character set and then extracted on another system using a different character set. When compiled with Unicode support enabled on platforms that support wide characters, zip now stores, in addition to the standard local path for backward compatibility, the UTF-8 translation of the path. This provides a common universal character set for storing paths that allows these paths to be fully extracted on other systems that support Unicode and to match as close as possible on systems that don’t.

On Win32 systems where paths are internally stored as Unicode but represented in the local character set, it’s possible that some paths will be skipped during a local character set directory scan. zip with Unicode support now can read and store these paths. Note that Win 9x systems and FAT file systems don’t fully support Unicode.

Be aware that console windows on Win32 and Unix, for example, sometimes don’t accurately show all characters due to how each operating system switches in character sets for display. However, directory navigation tools should show the correct paths if the needed fonts are loaded.

Command Line Format

This version of zip has updated command line processing and support for long options.

Short options take the form:

-s[-][s[-]...][value][=value][ value]

…where s is a one or two character short option. A short option that takes a value is last in an argument and anything after it is taken as the value. If the option can be negated and “” immediately follows the option, the option is negated. Short options can also be given as separate arguments

-s[-][value][=value][ value] -s[-][value][=value][ value] ...

Short options in general take values either as part of the same argument or as the following argument. An optional = is also supported. So -ttmmddyyyy-tt=mmddyyyy, and -tt mmddyyyy all work. The -x and -i options accept lists of values and use a slightly different format described below. See the -x and -i options.

Long options take the form

--longoption[-][=value][ value]

where the option starts with , has a multicharacter name, can include a trailing dash to negate the option (if the option supports it), and can have a value (option argument) specified by preceding it with = (no spaces). Values can also follow the argument. So –before-date=mmddyyyy and –before-date mmddyyyy both work.

Long option names can be shortened to the shortest unique abbreviation. See the option descriptions below for which support long options. To avoid confusion, avoid abbreviating a negatable option with an embedded dash (““) at the dash if you plan to negate it (the parser would consider a trailing dash, such as for the option –some-option using –some- as the option, as part of the name rather than a negating dash). This may be changed to force the last dash in –some- to be negating in the future.

Syntax

zip [-aABcdDeEfFghjklLmoqrRSTuvVwXyz!@$] [--longoption ...]  [-b path] 
    [-n suffixes] [-t date] [-tt date] [zipfile [file ...]]  [-xi list]

Options

-a–asciiOn systems using EBCDIC, this option translates files to ASCII format.
-A–adjust-sfxAdjust self-extracting executable archive. A self-extracting executable archive is created by prepending the “SFX” stub to an existing archive. The -A option tells zip to adjust the entry offsets stored in the archive to take into account this “preamble” data.
-AC–archive-clearThis option is a Windows-only option. Once archive is created (and tested if -T is used, which is recommended), clear the archive bits of files processed. Once the bits are cleared they are cleared permanently. You may want to use the -sf (show files) option to store the list of files processed in case the archive operation must be repeated. Also consider using the -MM (must match) option. Be sure to check out -DF as a possibly better way to do incremental backups.
-AS–archive-setThis option is a Windows-only option which only includes files that have the archive bit set. Directories are not stored when -AS is used, though by default the paths of entries, including directories, are stored as usual and can be used by most unzips to recreate directories.

The archive bit is set by the operating system when a file is modified and, if used with -AC-AS can provide an incremental backup capability. However, other applications can modify the archive bit and it may not be a reliable indicator of which files have changed since the last archive operation. Alternative ways to create incremental backups are using -t to use file dates, though this won’t catch old files copied to directories being archived, and -DF to create a differential archive.

-B–binaryForce files to be read as binary (default is text).
-b path–temp-path pathUse the specified path for the temporary zip archive. For example:

zip -b /tmp stuff *

…will put the temporary zip archive in the directory /tmp, copying over stuff.zip to the current directory when done. This option is useful when updating an existing archive and the file system containing this old archive does not have enough space to hold both old and new archives at the same time. It may also be useful when streaming in some cases to avoid the need for data descriptors. Note that using this option may require zip take additional time to copy the archive file when done to the destination file system.

-c–entry-commentsAdicione comentários de uma linha para cada arquivo. As operações de arquivo (adição, atualização) são feitas primeiro e o usuário é solicitado a fazer um comentário de uma linha para cada arquivo. Digite o comentário seguido de retorno, ou simplesmente retorne para nenhum comentário.
-d , –deleteRemova (exclua) entradas de um arquivo zip . Por exemplo:

zip -d foo foo / tom / lixo lixo / harry / \ * \ *. o

… removerá a entrada foo / tom / junk , todos os arquivos que começam com foo / harry / e todos os arquivos que terminam com .o (em qualquer caminho). Observe que a expansão do nome do caminho do shell foi inibida com barras invertidas, para que o zip possa ver os asteriscos , permitindo que o zip corresponda ao conteúdo do arquivo zip em vez do conteúdo do diretório atual. (As barras invertidas não são usadas nas plataformas baseadas no MSDOS.) Também pode usar aspas para escapar dos asteriscos, como em

zip -d foo foo / tom / lixo "foo / harry / *" "* .o"

Não escapar dos asteriscos em um sistema em que o shell expande curingas pode resultar na conversão dos asteriscos em uma lista de arquivos no diretório atual e na lista usada para excluir entradas do arquivo morto.

No MSDOS, -d diferencia maiúsculas de minúsculas quando corresponde a nomes no arquivo zip . Isso requer que os nomes dos arquivos sejam inseridos em maiúsculas se foram compactados por PKZIP em um sistema MSDOS. Consulte a opção -ic para ignorar maiúsculas e minúsculas no arquivo morto.

-db , –display-bytesExibe a contagem de bytes em execução, mostrando os bytes compactados e os bytes restantes.
-dc , –display-countsExiba uma contagem contínua de entradas compactadas e entradas ainda a serem processadas.
-dd , –display-dotsExiba pontos enquanto cada entrada é compactada (exceto nas portas que possuem seu próprio indicador de progresso). Veja -ds abaixo para definir o tamanho do ponto. O padrão é um ponto a cada 10 MB de arquivo de entrada processado. A opção -v também exibe pontos (anteriormente a uma taxa muito maior que essa, mas agora -v também assume o padrão de 10 MB) e essa taxa também é controlada por -ds .
-df , –dataforkNo MacOS, inclua apenas a bifurcação de dados compactada no arquivo morto. Bom para exportar arquivos para sistemas operacionais estrangeiros. Garfos de recursos serão ignorados.
-dg , –display-globaldotsExibir pontos de progresso para o arquivo em vez de para cada arquivo. O comando

zip -qdgds 10m

… desativará a maioria das saídas, exceto os pontos a cada 10 MB.

-ds size , –dot-size sizeDefina a quantidade de arquivo de entrada processada para cada ponto exibido. Consulte -dd para ativar a exibição de pontos. Definir esta opção implica -dd . O tamanho está no formato nm, em que n é um número e m é um multiplicador. Atualmente m pode ser k ( KB ), m ( MB ), g ( GB ) ou t ( TB ); portanto, se n for 100 e m for k , o tamanho será 100k, ou seja, 100 KB. O padrão é 10 MB.

o-v opção também exibe pontos e agora o padrão é 10 MB também. Essa taxa também é controlada por esta opção. Um tamanho de 0 desativa os pontos.

Esta opção não controla os pontos da mensagem “Digitalizando arquivos”, como varreduras zip para arquivos de entrada. O tamanho do ponto é fixado em 2 segundos ou um número fixo de entradas, o que for maior.

-du , –display-usizeExiba o tamanho não compactado de cada entrada.
-dv , –display-volumeExiba o número do volume (disco) em que cada entrada está sendo lida, se estiver lendo um arquivo existente e onde está sendo gravada.
-D , –no-dir-entradasNão crie entradas no arquivo zip para diretórios. As entradas de diretório são criadas por padrão para que seus atributos possam ser salvos no arquivo morto. A variável de ambiente ZIPOPT pode ser usada para alterar as opções padrão. Por exemplo, em Unix, com sh :

ZIPOPT = "- D"; exportar ZIPOPT

(A variável ZIPOPT pode ser usada para qualquer opção, incluindo -i e -x, usando um novo formato de opção detalhado abaixo e pode incluir várias opções.) A opção -D é uma abreviação de -x “* /”, mas a última anteriormente não pôde ser definido como padrão na variável de ambiente ZIPOPT , pois o conteúdo do ZIPOPT é inserido próximo ao início da linha de comando e a lista de arquivos precisava terminar no final da linha.

Esta versão do zip permite as opções -x e -i no ZIPOPT se o formulário

-x arquivo ... @

… é usado, onde o @ (um argumento que é apenas @ ) termina a lista.

-DF , –diferença-arquivoCrie um arquivo que contenha todos os arquivos novos e alterados desde que o arquivo original foi criado. Para que isso funcione, a lista de arquivos de entrada e o diretório atual devem ser os mesmos da operação zip original .

Por exemplo, se o arquivo existente foi criado usando

zip -r foofull.

do diretório bar , o comando

zip -r foofull. -DF - de novo

… também no diretório bar cria o arquivo foonew apenas com os arquivos que não estão disponíveis e os arquivos em que o tamanho ou o tempo do arquivo não coincidem com os que estão disponíveis.

Observe que a variável de ambiente TZ do fuso horário deve ser definida de acordo com o fuso horário local para que esta opção funcione corretamente. Uma alteração no fuso horário desde a criação do arquivo original pode resultar na correspondência sem tempo e com a inclusão de todos os arquivos.

Uma abordagem possível para fazer backup de um diretório pode ser criar um arquivo normal do conteúdo do diretório como um backup completo e, em seguida, usar esta opção para criar backups incrementais.

-e , –encryptEncrypt the contents of the zip archive using a password that is entered on the terminal in response to a prompt (this will not be echoed; if standard error is not a tty, zip will exit with an error). The password prompt is repeated to save the user from typing errors.
-E–longnamesOn OS/2, use the .LONGNAME Extended Attribute (if found) as the file name.
-f–freshenReplace (freshen) an existing entry in the zip archive only if it has been modified more recently than the version already in the zip archive; unlike the update option (-u) this will not add files that are not already in the zip archive. For example:

zip -f foo

This command should be run from the same directory from which the original zip command was run, since paths stored in zip archives are always relative.

Note that the timezone environment variable TZ should be set according to the local timezone for the -f-u and -o options to work correctly.

The reasons behind this are somewhat subtle but have to do with the differences between the Unix-format file times (always in GMT) and most of the other operating systems (always local time) and the necessity to compare the two. A typical TZ value is “MET-1MEST” (Middle European time with automatic adjustment for “summertime” or Daylight Savings Time).

The format is TTThhDDD, where TTT is the time zone such as PST, hh is the difference between GMT and local time such as -1 above, and DDD is the time zone when daylight savings time is in effect. Leave off the DDD if there is no daylight savings time. For the US Eastern time zone: EST5EDT.

-F–fix-FF–fixfixFix the zip archive. The -F option can be used if some portions of the archive are missing, but requires a reasonably intact central directory. The input archive is scanned as usual, but zip ignores some problems. The resulting archive should be valid, but any inconsistent entries will be left out.

When doubled as in -FF, the archive is scanned from the beginning and zip scans for special signatures to identify the limits between the archive members. The single -F is more reliable if the archive is not too much damaged, so try this option first.

If the archive is too damaged or the end has been truncated, you must use -FF. This option is a change from zip 2.32, where the -F option can read a truncated archive. The -F option now more reliably fixes archives with minor damage and the -FF option is needed to fix archives where -F might have been sufficient before.

Neither option will recover archives that have been incorrectly transferred in ascii mode instead of binary. After the repair, the -t option of unzip may show that some files have a bad CRC. Such files cannot be recovered; you can remove them from the archive using the -d option of zip.

Note that -FF may have trouble fixing archives that include an embedded zip archive that was stored (without compression) in the archive and, depending on the damage, it may find the entries in the embedded archive rather than the archive itself. Try -F first as it does not have this problem.

The format of the fix commands have changed. For example, to fix the damaged archive foo.zip,

zip -F foo --out foofix

…tries to read the entries normally, copying good entries to the new archive foofix.zip. If this doesn’t work, as when the archive is truncated, or if some entries you know are in the archive are missed, then try

zip -FF foo --out foofixfix

…and compare the resulting archive to the archive created by -F. The -FF option may create an inconsistent archive. Depending on what is damaged, you can then use the -F option to fix that archive.

A split archive with missing split files can be fixed using -F if you have the last split of the archive (the .zip file). If this file is missing, you must use -FF to fix the archive, which will prompt you for the splits you have.

Currently the fix options can’t recover entries that have a bad checksum or are otherwise damaged.

-FI–fifoOn Unix, normally zip skips reading any FIFOs (named pipes) encountered, as zip can hang if the FIFO is not being fed. This option tells zip to read the contents of any FIFO it finds.
-FS–filesyncSynchronize the contents of an archive with the files on the OS. Normally when an archive is updated, new files are added and changed files are updated but files that no longer exist on the OS are not deleted from the archive. This option enables a new mode that checks entries in the archive against the file system. If the file time and file size of the entry matches that of the OS file, the entry is copied from the old archive instead of being read from the file system and compressed. If the OS file has changed, the entry is read and compressed as usual. If the entry in the archive does not match a file on the OS, the entry is deleted. Enabling this option should create archives that are the same as new archives, but since existing entries are copied instead of compressed, updating an existing archive with -FS can be much faster than creating a new archive. Also consider using -u for updating an archive.

For this option to work, the archive should be updated from the same directory it was created in so the relative paths match. If few files are being copied from the old archive, it may be faster to create a new archive instead.

Note that the timezone environment variable TZ should be set according to the local timezone for this option to work correctly. A change in timezone since the original archive was created could result in no times matching and recompression of all files.

This option deletes files from the archive. If you need to preserve the original archive, make a copy of the archive first or use the –out option to output the updated archive to a new file. Even though it may be slower, creating a new archive with a new archive name is safer, avoids mismatches between archive and OS paths, and is preferred.

-g–growGrow (append to) the specified zip archive, instead of creating a new one. 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 archive member must be updated or deleted.
-h-?–helpDisplay the zip help information (this also appears if zip is run with no arguments).
-h2–more-helpDisplay extended help including more on command line format, pattern matching, and more obscure options.
-i files–include filesInclude only the specified files, as in:

zip -r foo . -i \*.c

…which will include only the files that end in .c in the current directory and its subdirectories. (Note for PKZIP users: the equivalent command is

pkzip -rP foo *.c

PKZIP does not allow recursion in directories other than the current one.) The backslash avoids the shell file name substitution, so that the name matching is performed by zip at all directory levels. [This option is for Unix and other systems where “\” escapes the next character.] So to include dir, a directory directly under the current directory, use:

zip -r foo . -i dir/\*

or:

zip -r foo . -i "dir/*"

…to match paths such as dir/a and dir/b/file.c. Note that currently the trailing / is needed for directories (as in:

zip -r foo . -i dir/

…to include directory dir).

The long option form of the first example is:

zip -r foo . --include \*.c

…and does the same thing as the short option form.

Though the command syntax used to require -i at the end of the command line, this version actually allows -i (or –include) anywhere. The list of files terminates at the next argument starting with , the end of the command line, or the list terminator @ (an argument that is just @). So the above can be given as:

zip -i \*.c @ -r foo .

…for example. There must be a space between the option and the first file of a list. For just one file you can use the single value form:

zip -i\*.c -r foo .

(no space between option and value) or:

zip --include=\*.c -r foo .

…as additional examples. The single value forms are not recommended because they can be confusing and, in particular, the -ifile format can cause problems if the first letter of file combines with i to form a two-letter option starting with i. Use -sc to see how your command line will be parsed.

Also possible:

zip -r foo  . [email protected]

…which will only include the files in the current directory and its subdirectories that match the patterns in the file include.lst.

Files to -i and -x are patterns matching internal archive paths. See -R for more on patterns.

-I–no-imageOn Acorn RISC OS, this option instructs zip not to scan through Image files. When used, zip will not consider Image files (eg. DOS partitions or Spark archives when SparkFS is loaded) as directories but will store them as single files.

For example, if you have SparkFS loaded, zipping a Spark archive will result in a zipfile containing a directory (and its content) while using the ‘I‘ option will result in a zipfile containing a Spark archive. Obviously this second case will also be obtained (without the ‘I‘ option) if SparkFS isn’t loaded.

-ic–ignore-caseOn VMS or Windows systems, ignore case when matching archive entries. This option is only available on systems where the case of files is ignored. On systems with case-insensitive file systems, case is normally ignored when matching files on the file system but is not ignored for -f (freshen), -d (delete), -U (copy), and similar modes when matching against archive entries (currently -f ignores case on VMS) because archive entries can be from systems where case does matter and names that are the same except for case can exist in an archive. The -ic option makes all matching case insensitive. This option can result in multiple archive entries matching a command line pattern.
-j–junk-pathsStore just the name of a saved file (without the path), and do not store directory names. By default, zip will store the full path, relative to the current directory.
-jj–absolute-pathOn macOS, record Fullpath (+ Volname). The complete path including volume will be stored. By default the relative path will be stored.
-J–junk-sfxStrip any prepended data (e.g., a SFX stub) from the archive.
-k–DOS-namesAttempt to convert the names and paths to conform to MSDOS, store only the MSDOS attribute (just the user write attribute from Unix), and mark the entry as made under MSDOS (even though it was not); for compatibility with PKUNZIP under MSDOS which cannot handle certain names such as those with two dots.
-l–to-crlfTranslate the Unix end-of-line character LF into the MSDOS convention CR LF. This option should not be used on binary files. This option can be used on Unix if the zip file is intended for PKUNZIP under MSDOS. If the input files already contain CR LF, this option adds an extra CR. This option is to ensure that unzip -a on Unix will get back an exact copy of the original file, to undo the effect of zip -l. See -ll for how binary files are handled.
-la–log-appendAppend to existing logfile. Default is to overwrite.
-lf logfilepath–logfile-path logfilepathOpen a logfile at the given path. By default any existing file at that location is overwritten, but the -la option will result in an existing file being opened and the new log information appended to any existing information. Only warnings and errors are written to the log unless the -li option is also given, then all information messages are also written to the log.
-li–log-infoInclude information messages, such as file names being zipped, in the log. The default is to only include the command line, any warnings and errors, and the final status.
-ll–from-crlfTranslate the MSDOS end-of-line CR LF into Unix LF. This option should not be used on binary files. This option can be used on MSDOS if the zip file is intended for unzip under Unix. If the file is converted and the file is later determined to be binary a warning is issued and the file is probably corrupted. In this release if -ll detects binary in the first buffer read from a file, zip now issues a warning and skips line end conversion on the file. This check seems to catch all binary files tested, but the original check remains and if a converted file is later determined to be binary that warning is still issued. A new algorithm is now being used for binary detection that should allow line end conversion of text files in UTF-8 and similar encodings.
-L–licenseDisplay the zip license.
-m–moveMove the specified files into the zip archive; actually, this deletes the 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 option 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 removing all input files.
-MM–must-matchAll input patterns must match at least one file and all input files found must be readable. Normally when an input pattern does not match a file the “name not matched” warning is issued and when an input file has been found but later is missing or not readable a missing or not readable warning is issued. In either case zip continues creating the archive, with missing or unreadable new files being skipped and files already in the archive remaining unchanged. After the archive is created, if any files were not readable, zip returns the OPEN error code (18 on most systems) instead of the normal success return (0 on most systems). With -MM set, zip exits as soon as an input pattern is not matched (whenever the “name not matched” warning would be issued) or when an input file is not readable. In either case zip exits with an OPEN error and no archive is created.

This option is useful when a known list of files is to be zipped so any missing or unreadable files will result in an error. It is less useful when used with wildcards, but zip will still exit with an error if any input pattern doesn’t match at least one file and if any matched files are unreadable. If you want to create the archive anyway and only need to know if files were skipped, don’t use -MM and just check the return code. Also -lf could be useful.

-n suffixes–suffixes suffixesDo not attempt to compress files named with the given suffixes. Such files are stored (0% compression) in the output zip file, so that zip doesn’t waste its time trying to compress them. The suffixes are separated by either colons or semicolons. For example:

zip -rn .Z:.zip:.tiff:.gif:.snd  foo foo

will copy everything from foo into foo.zip, but will store any files that end in .Z.zip.tiff.gif, or .snd without trying to compress them (image and sound files often have their own specialized compression methods). By default, zip does not compress files with extensions in the list .Z:.zip:.zoo:.arc:.lzh:.arj. Such files are stored directly in the output archive. The environment variable ZIPOPT can be used to change the default options. For example under Unix with csh:

setenv ZIPOPT "-n .gif:.zip"

To attempt compression on all files, use:

zip -n : foo

The maximum compression option -9 also attempts compression on all files regardless of extension.

On Acorn RISC OS systems the suffixes are actually filetypes (3 hex digit format). By default, zip does not compress files with filetypes in the list DDC:D96:68E (i.e. Archives, CFS files and PackDir files).

-nw–no-wildDo not perform internal wildcard processing (shell processing of wildcards is still done by the shell unless the arguments are escaped). Useful if a list of paths is being read and no wildcard substitution is desired.
-N–notes[Amiga, MacOS] Save Amiga or MacOS filenotes as zipfile comments. They can be restored by using the -N option of unzip. If -c is used also, you are prompted for comments only for those files that do not have filenotes.
-o–latest-timeSet the “last modified” time of the zip archive to the latest (oldest) “last modified” time found among the entries in the zip archive. This option can be used without any other operations, if desired. For example:

zip -o foo

…will change the last modified time of foo.zip to the latest time of the entries in foo.zip.

-O output-file–output-file output-fileProcess the archive changes as usual, but instead of updating the existing archive, output the new archive to output-file. Useful for updating an archive without changing the existing archive and the input archive must be a different file than the output archive.

This option can be used to create updated split archives. It can also be used with -U to copy entries from an existing archive to a new archive.

Another use is converting zip files from one split size to another. For instance, to convert an archive with 700 MB CD splits to one with 2 GB DVD splits, can use:

zip -s 2g cd-split.zip --out dvd-split.zip

…which uses copy mode. See -U below. Also:

zip -s 0 split.zip --out unsplit.zip

…will convert a split archive to a single-file archive.

Copy mode will convert stream entries (using data descriptors and which should be compatible with most unzips) to normal entries (which should be compatible with all unzips), except if standard encryption was used. For archives with encrypted entries, zipcloak will decrypt the entries and convert them to normal entries.

-p–pathsInclude relative file paths as part of the names of files stored in the archive. This option is the default. The -j option junks the paths and just stores the names of the files.
-P password–password passwordUse password to encrypt zipfile entries (if any). THIS IS INSECURE! Many multi-user operating systems 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 instead of the relatively weak standard encryption provided by zipfile utilities.)
-q–quietQuiet mode; eliminate informational messages and comment prompts. (Useful, for example, in shell scripts and background tasks).
-r–recurse-pathsTravel the directory structure recursively; for example:

zip -r foo.zip foo

or more concisely

zip -r foo foo

In this case, all the files and directories in foo are saved in an archive named foo.zip, including files with names starting with “.“, since the recursion does not use the shell’s file-name substitution mechanism. If you want to include only a specific subset of the files in directory foo and its subdirectories, use the -i option to specify the pattern of files to be included. You should not use -r with the name “.*“, since that matches “..” which will attempt to zip up the parent directory (probably not what was intended).

Multiple source directories are allowed:

zip -r foo foo1 foo2

…which first zips up foo1 and then foo2, going down each directory.

Note that while wildcards to -r are typically resolved while recursing down directories in the file system, any -R-x, and -i wildcards are applied to internal archive pathnames once the directories are scanned. To have wildcards apply to files in subdirectories when recursing on Unix and similar systems where the shell does wildcard substitution, either escape all wildcards or put all arguments with wildcards in quotes. This lets zip see the wildcards and match files in subdirectories using them as it recurses.

-R–recurse-patternsTravel the directory structure recursively starting at the current directory; for example:

zip -R foo "*.c"

In this case, all the files matching *.c in the tree starting at the current directory are stored into a zip archive named foo.zip. Note that *.c will match file.ca/file.c and a/b/.c. More than one pattern can be listed as separate arguments. Note for PKZIP users: the equivalent command is

pkzip -rP foo *.c

Patterns are relative file paths as they appear in the archive, or will after zipping, and can have optional wildcards in them. For example, given the current directory is foo and under it are directories foo1 and foo2 and in foo1 is the file bar.c,

zip -R foo/*

…will zip up foofoo/foo1foo/foo1/bar.c, and foo/foo2.

zip -R */bar.c

…will zip up foo/foo1/bar.c. See the note for -r on escaping wildcards.

-RE–regex[WIN32] Before zip 3.0, regular expression list matching was enabled by default on Windows platforms. Because of confusion resulting from the need to escape “[“ and “]” in names, it is now off by default for Windows so “[” and “]” are just normal characters in names. This option enables [] matching again.
-s splitsize–split-size splitsizeEnable creating a split archive and set the split size. A split archive is an archive that could be split over many files. As the 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 archives are stored in numbered files. For example, if the output archive is named archive and three splits are required, the resulting archive will be in the three files archive.z01archive.z02, and archive.zip. Do not change the numbering of these files or the archive will not be readable as these are used to determine the order the splits are read.

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 64 k is the minimum split size, numbers without multipliers default to megabytes. For example, to create a split archive called foo with the contents of the bar directory with splits of 670 MB that might be useful for burning on CDs, the command:

zip -s 670m -r foo bar

could be used.

Currently the old splits of a split archive are not excluded from a new archive, but they can be specifically excluded. If possible, keep the input and output archives out of the path being zipped when creating split archives.

Using -s without -sp as above creates all the splits where foo is being written, in this case the current directory. This split mode updates the splits as the archive is being created, requiring all splits to remain writable, but creates split archives that are readable by any unzip that supports split archives. See -sp below for enabling split pause mode that allows splits to be written directly to removable media.

The option -sv can be used to enable verbose splitting and provide details of how the splitting is being done. The -sb option can be used to ring the bell when zip pauses for the next split destination.

Split archives cannot be updated, but see the -O (–out) option for how a split archive can be updated as it is copied to a new archive. A split archive can also be converted into a single-file archive using a split size of 0 or negating the -s option:

zip -s 0 split.zip --out single.zip

Also see -U (–copy) for more on using copy mode.

-sb–split-bellIf splitting and using split pause mode, ring the bell when zip pauses for each split destination.
-sc–show-commandShow the command line starting zip as processed and exit. The new command parser permutes the arguments, putting all options and any values associated with them before any non-option arguments, which allows an option to appear anywhere in the command line as long as any values that go with the option go with it. This option displays the command line as zip sees it, including any arguments from the environment such as from the ZIPOPT variable. Where allowed, options later in the command line can override options earlier in the command line.
-sf–show-filesShow the files that would be operated on, then exit. For instance, if creating a new archive, this will list the files that would be added. If the option is negated (-sf-), output only to an open log file. Screen display is not recommended for large lists.
-so–show-optionsShow all available options supported by zip as compiled on the current system. As this command reads the option table, it should include all options. Each line includes the short option (if defined), the long option (if defined), the format of any value that goes with the option, if the option can be negated, and a small description. The value format can be no value, required value, optional value, single character value, number value, or a list of values. The output of this option is not intended to show how to use any option but only show what options are available.
-sp–split-pauseIf splitting is enabled with -s, enable split pause mode. This option creates split archives as -s does, but stream writing is used so each split can be closed as soon as it is written and zip will pause between each split to allow changing split destination or media.

Though this split mode allows writing splits directly to removable media, it uses stream archive format that may not be readable by some unzips. Before relying on splits created with -sp, test a split archive with the unzip you will be using.

To convert a stream split archive (created with -sp) to a standard archive see the –out option.

-su–show-unicodeAs -sf, but also show Unicode version of the path if exists.
-sU–show-just-unicodeAs -sf, but only show Unicode version of the path if exists, otherwise show the standard version of the path.
-sv–split-verboseEnable various verbose messages while splitting, showing how the splitting is being done.
-S–system-hiddenInclude system and hidden files. On MacOS, includes finder invisible files, which are ignored otherwise.
-t mmddyyyy–from-date mmddyyyyDo not operate on files modified prior to the specified date, where mm is the month (0012), dd is the day of the month (0131), and yyyy is the year. The ISO 8601 date format yyyymmdd is also accepted. For example:

zip -rt 12071991 infamy foo
zip -rt 1991-12-07 infamy foo

…will add all the files in foo and its subdirectories that were last modified on or after 7 December 1991, to the zip archive infamy.zip.

-tt mmddyyyy–before-date mmddyyyyDo not operate on files modified after or at the specified date, where mm is the month (0012), dd is the day of the month (0131), and yyyy is the year. The ISO 8601 date format yyyymmdd is also accepted. For example:

zip -rtt 11301995 infamy foo
zip -rtt 1995-11-30 infamy foo

…will add all the files in foo and its subdirectories that were last modified before 30 November 1995, to the zip archive infamy.zip.

-T–testTest the integrity of the new zip file. If the check fails, the old zip file is unchanged and (with the -m option) no input files are removed.
-TT cmd–unzip-command cmdUse command cmd instead of ‘unzip -tqq‘ to test an archive when the -T option is used. On Unix, to use a copy of unzip in the current directory instead of the standard system unzip, could use:

zip archive file1 file2 -T -TT "./unzip -tqq"

In cmd{} is replaced by the name of the temporary archive, otherwise the name of the archive is appended to the end of the command. The return code is checked for success (0 on Unix).

-u–updateReplace (update) an existing entry in the zip archive only if it has been modified more recently than the version already in the zip archive. For example:

zip -u stuff *

…will add any new files in the current directory, and update any files which have been modified since the zip archive stuff.zip was last created/modified (note that zip will not try to pack stuff.zip into itself when you do this).

Note that the -u option with no input file arguments acts like the -f (freshen) option.

-U–copy-entriesCopy entries from one archive to another. Requires the –out option to specify a different output file than the input archive. Copy mode is the reverse of -d (delete). When delete is being used with –out, the selected entries are deleted from the archive and all other entries are copied to the new archive, while copy mode selects the files to include in the new archive. Unlike -u (update), input patterns on the command line are matched against archive entries only and not the file system files. For instance,

zip inarchive "*.c" --copy --out outarchive

… copia entradas com nomes que terminam em .c de inarchive para outarchive. O curinga deve ser escapado em alguns sistemas para impedir que o shell substitua nomes de arquivos do sistema de arquivos que podem não ter relevância para as entradas no arquivo morto.

Se nenhum arquivo de entrada aparecer na linha de comando e –out for usado, o modo de cópia será assumido:

zip inarchive - out outarchive

Esta opção é útil para alterar o tamanho da divisão, por exemplo. Criptografar e descriptografar entradas ainda não são suportadas usando o modo de cópia. Use zipcloak para isso.

-UN v , –unicode vDetermine o que o zip deve fazer com os nomes de arquivo Unicode. O zip 3.0, além do caminho padrão do arquivo, agora inclui a conversão UTF-8 do caminho, se o caminho de entrada não for totalmente ASCII de 7 bits. Quando uma entrada está ausente no caminho Unicode, o zip reverte para o caminho padrão do arquivo. O problema de usar o caminho padrão é que esse caminho está no conjunto de caracteres local do zip que criou a entrada, que pode conter caracteres que não são válidos no conjunto de caracteres usado pelo descompactação . Quando zip estiver lendo um archive, se uma entrada também tiver um caminho Unicode, zipagora usa o caminho Unicode para recriar o caminho padrão usando o conjunto de caracteres local atual.

Essa opção pode ser usada para determinar o que o zip deve fazer com esse caminho se houver uma incompatibilidade entre o caminho padrão armazenado e o caminho UTF-8 armazenado (o que pode acontecer se o caminho padrão for atualizado). Em todos os casos, se houver uma incompatibilidade, é assumido que o caminho padrão é mais atual e o zip o usa. Os valores para v são

qsaia se os caminhos não coincidirem
Wavisar, continue com o caminho padrão
Euignorar, continue com o caminho padrão
nsem Unicode, não use caminhos Unicode

O padrão é avisar e continuar.

Os caracteres que não são válidos no conjunto de caracteres atual são escapados como #U xxxx e #L xxxxxx , em que x é um caractere ASCII para um dígito hexadecimal. O primeiro é usado se um número de caracteres de 16 bits for suficiente para representar o caractere Unicode e o segundo se o caractere precisar de mais de 16 bits para representar seu código de caractere Unicode. Configurando -UN para

efuga

como em:

arquivo zip -sU -UN = e

… força o zip a escapar de todos os caracteres que não são imprimíveis em ASCII de 7 bits.

Normalmente, o zip armazena o UTF-8 diretamente no campo de caminho padrão nos sistemas em que o UTF-8 é o conjunto de caracteres atual e, de outra forma, armazena o UTF-8 nos novos campos extras. A opção

vocêUTF-8

como em

arquivo zip dir -r -UN = UTF8

… força o zip a armazenar o UTF-8 como nativo no arquivo morto. Observe que armazenar UTF-8 diretamente é o padrão nos sistemas Unix que o suportam. Essa opção pode ser útil em sistemas Windows em que o caminho de escape é muito grande para ser um caminho válido e a versão UTF-8 do caminho é menor, mas o UTF-8 nativo não é compatível com versões anteriores nos sistemas Windows.

-v , –verboseModo detalhado ou imprima as informações da versão de diagnóstico.

Normalmente, quando aplicada a operações reais, essa opção permite a exibição de um indicador de progresso durante a compactação (consulte -dd para obter mais informações sobre pontos) e solicita informações detalhadas de diagnóstico sobre as esquisitices da estrutura do arquivo zip.

No entanto, quando -vé o único argumento da linha de comando em que uma tela de diagnóstico é impressa. Agora, isso deve funcionar mesmo que o stdout seja redirecionado para um arquivo, facilitando o salvamento das informações para o envio com relatórios de erros ao Info-ZIP. A tela de versão fornece ao cabeçalho da tela de ajuda o nome do programa, a versão e a data de lançamento, alguns ponteiros para os sites de distribuição e de distribuição Info-ZIP e mostra informações sobre o ambiente de destino (tipo e versão do compilador, versão do SO, data de compilação e recursos opcionais ativados usados ​​para criar o executável zip ).

-V , -VMS-portátilNo VMS, salve os atributos do arquivo VMS. (Os arquivos são truncados no EOF.) Quando um arquivo -V é descompactado em um sistema não-VMS, alguns tipos de arquivo (principalmente arquivos de texto Stream_LF e arquivos binários puros, como o fixo-512) devem ser extraídos intactos. Arquivos indexados e tipos de arquivos com tamanhos de registro incorporados (principalmente tipos de registros de tamanho variável) provavelmente serão vistos como corrompidos em outros lugares.
-VV , – específico do VMSNo VMS, salve os atributos do arquivo VMS e todos os blocos alocados em um arquivo, incluindo quaisquer dados além do EOF. Útil para mover arquivos mal formados entre sistemas VMS. Quando um arquivo -VV é descompactado em um sistema não-VMS, quase todos os arquivos aparecem corrompidos.
-w , –VMS-versõesNo VMS, anexe o número da versão dos arquivos ao nome, incluindo várias versões dos arquivos. O padrão é usar apenas a versão mais recente de um arquivo especificado.
-ww , –VMS-dot-versõesNo VMS, anexe o número da versão dos arquivos ao nome, incluindo várias versões dos arquivos, usando o formato nnn . O padrão é usar apenas a versão mais recente de um arquivo especificado.
-ws , –wild-stop-dirsOs curingas correspondem apenas no nível do diretório. Normalmente, o zip lida com caminhos como strings e dados os caminhos

/foo/bar/dir/file1.c
/foo/bar/file2.c

um padrão de entrada como

/ foo / bar / *

Normalmente iria coincidir com os dois caminhos, a * correspondência dir / file1.c e file2.c . Observe que, no primeiro caso, um limite de diretório ( / ) foi ultrapassado na correspondência. Com -ws, nenhum limite de diretório será incluído na correspondência, tornando os curingas locais em um nível de diretório específico. Portanto, com -ws ativado, apenas o segundo caminho seria correspondido.

Ao usar -ws , use ** para corresponder entre os limites do diretório como * normalmente.

arquivos -x , – arquivos excluídosExclua explicitamente os arquivos especificados, como em:

zip -r foo foo -x \ *. o

…which will include the contents of foo in foo.zip while excluding all the files that end in .o. The backslash avoids the shell file name substitution, so that the name matching is performed by zip at all directory levels.

Also possible:

zip -r foo foo [email protected]

…which will include the contents of foo in foo.zip while excluding all the files that match the patterns in the file exclude.lst.

The long option forms of the above are

zip -r foo foo --exclude \*.o

and

zip -r foo foo --exclude @exclude.lst

Multiple patterns can be specified, as in:

zip -r foo foo -x \*.o \*.c

If there is no space between -x and the pattern, just one value is assumed (no list):

zip -r foo foo -x\*.o

See -i for more on include and exclude.

-X–no-extraDo not save extra file attributes (Extended Attributes on OS/2, uid/gid and file times on Unix). The zip format uses extra fields to include additional information for each entry. Some extra fields are specific to particular systems while others are applicable to all systems. Normally when zip reads entries from an existing archive, it reads the extra fields it knows, strips the rest, and adds the extra fields applicable to that system. With -X, zip strips all old fields and only includes the Unicode and Zip64 extra fields (currently these two extra fields cannot be disabled).

Negating this option, -X-, includes all the default extra fields, but also copies over any unrecognized extra fields.

-y–symlinksFor UNIX and VMS (V8.3 and later), store symbolic links as such in the zip archive, instead of compressing and storing the file referred to by the link. This option can avoid multiple copies of files being included in the archive as zip recurses the directory trees and accesses files directly and by links.
-z–archive-commentPrompt for a multi-line comment for the entire zip archive. The comment is ended by a line containing just a period, or an end of file condition (^D on Unix, ^Z on MSDOS, OS/2, and VMS). The comment can be taken from a file:

zip -z foo < foowhat
-Z cm–compression-method cmSet the default compression method. Currently the main methods supported by zip are store and deflate. Compression method can be set to:

storeSetting the compression method to store forces zip to store entries with no compression. This method is generally faster than compressing entries, but results in no space savings. This method is the same as using -0 (compression level zero).
deflateThis method is the default method for zip. If zip determines that storing is better than deflation, the entry will be stored instead.
bzip2If bzip2 support is compiled in, this compression method also becomes available. Only some modern unzips currently support the bzip2 compression method, so test the unzip you will be using before relying on archives using this method (compression method 12).

For example, to add bar.c to archive foo using bzip2 compression:

zip -Z bzip2 foo bar.c

The compression method can be abbreviated:

zip -Zb foo bar.c
#Regulate the speed of compression using the specified digit #, between 0 and 9, where -0 indicates no compression (store all files), -1 indicates the fastest compression speed (less compression) and -9 indicates the slowest compression speed (optimal compression, ignores the suffix list). The default compression level is -6.

Though still being worked, the intention is this setting will control compression speed for all compression methods. Currently only deflation is controlled.

-!–use-privilegesOn Windows, use privileges (if granted) to obtain all aspects of WinNT security.
-@–names-stdinTake the list of input files from standard input. Only one file name per line.
-$–volume-labelInclude the volume label for the drive holding the first file to be compressed. If you want to include only the volume label or to force a specific drive, use the drive name as first file name, as in:

zip -$ foo a: c:bar

Environment

zip uses the following environment variables:

ZIPOPTContains default options that will be used when running zip. The contents of this environment variable will get added to the command line just after the zip command.
ZIPAn alias for ZIPOPT, except on RISC OS and VMS.

No Risc e no VMS, existem variáveis ​​de ambiente especiais adicionais; consulte sua documentação para obter detalhes.

Exemplos

material zip *

Cria o arquivo stuff.zip (supondo que ele não exista) e coloca todos os arquivos no diretório atual, em formato compactado (o sufixo .zip é adicionado automaticamente, a menos que o nome do arquivo já contenha um ponto; isso permite explícita especificação de outros sufixos).

zip stuff. * *

O mesmo que o comando acima, mas também inclui arquivos começando com um ponto (exceto os nomes de diretório especiais ” . ” E ” .. “.

zip -r foo foo

Compacta o subdiretório foo inteiro em um arquivo morto , foo.zip , e grava o nome do diretório com cada arquivo.

zip -j foo foo / *

Igual ao comando acima, mas, diferentemente de -r , a opção -j não registrará o nome do diretório, apenas os nomes dos próprios arquivos.

zip -s 2g -r split.zip foo

Cria um arquivo dividido do diretório foo com divisões não maiores que 2 GB cada. Se foo continha 5 GB de conteúdo e o conteúdo fosse armazenado no archive dividido sem compactação (para simplificar este exemplo), isso criaria três divisões, split.z01 em 2 GB, split.z02 em 2 GB e split.zip com pouco mais de 1 GB.

compactar – Comprime um arquivo ou arquivos.
tar – Crie, modifique, liste o conteúdo e extraia arquivos de arquivos tar.
descompacte – liste , teste e extraia arquivos compactados em um arquivo zip.
gzip, gunzip, zcat – Crie, modifique, liste o conteúdo e extraia arquivos dos arquivos zip do GNU.
zipinfo – Exibe informações técnicas sobre um arquivo zip.

22 de novembro de 2019

Sobre nós

A Linux Force Brasil é uma empresa que ama a arte de ensinar. Nossa missão é criar talentos para a área de tecnologia e atender com excelência nossos clientes.

CNPJ: 13.299.207/0001-50
SAC:         0800 721 7901

[email protected]

Comercial  Comercial: (11) 3796-5900

Suporte:    (11) 3796-5900
[email protected]

Copyright © Linux Force Security  - Desde 2011.