[Linux]常用命令之【tar/zip/unzip/gzip/gunzip/Z】

1 tar | 打包工具

1.1 .tar.gz 的区别

.tar 只是进行打包,并没有压缩。 则:
  用tar-cvf进行打包
  用tar-xvf进行解包。

.tar.gz 是既打包又压缩 ,则:
  tar –czvf [压缩包名] [文件或目录] // 打包,且使用 gzip 压缩 
      注: 生成的【压缩包的包名】可随意命名,tar命令做解压、压缩时 均不会受影响。
           但建议,尽量规范化: 使用了 tar 打包,则:包名的文件格式后缀 第1段子后缀命名为 file.tar ; 以此类推,使用了 gizp 做压缩,则: .gz;若 二者均有使用,则: file.tar.gz
  tar –xzvf [压缩包名]             // 解包,且该包为 gzip 的压缩包
      注: -z,--gzip, --gunzip, --ungzip : 通过 gzip 过滤归档。如果被解压的包并没有通过gz压缩,则 使用了-z参数会报错(gzip: stdin: not in gzip format)

.gz 只压缩。只能针对文件。如果需要对一个目录下的全部文件压缩,则:
  gzip -r [目录]   // 文件夹压缩
  gzip [文件名]    // 文件压缩
  gzip –d [文件名] // 文件解压

1.2 tar 命令参数详解

  • tar 命令参数详解
shell# man tar
NAME
       tar - manual page for tar 1.26

SYNOPSIS
       tar [OPTION...] [FILE]...

DESCRIPTION
       GNU `tar' saves many files together into a single tape or disk archive, and can restore individual files from the archive.

       Note  that  this  manual page contains just very brief description (or more like a list of possible functionality) originally generated by the
       help2man utility.  The full documentation for tar is maintained as a Texinfo manual.  If the info and tar programs are properly  installed  at
       your site, the command `info tar' should give you access to the complete manual.

EXAMPLES
       tar -cf archive.tar foo bar
              # Create archive.tar from files foo and bar.

       tar -tvf archive.tar
              # List all files in archive.tar verbosely.

       tar -xf archive.tar
              # Extract all files from archive.tar.

DEFAULTS
       *This* tar installation defaults to:

       --format=gnu -f- -b20 --quoting-style=escape --rmt-command=/sbin/rmt --rsh-command=/usr/bin/rsh

Main operation mode:
       -A, --catenate, --concatenate
              append tar files to an archive

       -c, --create
              create a new archive

       -d, --diff, --compare
              find differences between archive and file system

       --delete
              delete from the archive (not on mag tapes!)

       -r, --append
              append files to the end of an archive

       -t, --list
              list the contents of an archive

       --test-label
              test the archive volume label and exit

       -u, --update
              only append files newer than copy in archive

       -x, --extract, --get
              extract files from an archive

Common options:
       -C, --directory=DIR
              change to directory DIR

       -f, --file=ARCHIVE
              use archive file or device ARCHIVE

       -j, --bzip2
              filter the archive through bzip2

        -J, --xz
              filter the archive through xz

       -p, --preserve-permissions
              extract  information  about  file permissions (default for superuser)

       -v, --verbose
              verbosely list files processed

       -z, --gzip
              filter the archive through gzip

Operation modifiers:
       --check-device
              check device numbers when creating incremental archives (default)

       -g, --listed-incremental=FILE
              handle new GNU-format incremental backup

       -G, --incremental
              handle old GNU-format incremental backup

       --ignore-failed-read
              do not exit with nonzero on unreadable files

       --level=NUMBER
              dump level for created listed-incremental archive

       -n, --seek
              archive is seekable

       --no-check-device
              do not check device numbers when creating incremental archives

       --no-seek
              archive is not seekable

       --occurrence[=NUMBER]
              process  only the NUMBERth occurrence of each file in the archive; this option is valid only in conjunction with one of the subcommands
              --delete, --diff, --extract or --list and when a list of files is given either on the  command  line  or  via  the  -T  option;  NUMBER
              defaults to 1

       --sparse-version=MAJOR[.MINOR]
              set version of the sparse format to use (implies --sparse)

       -S, --sparse
              handle sparse files efficiently

Overwrite control:
       -k, --keep-old-files
              don't replace existing files when extracting, treat them as errors

       --keep-newer-files
              don't replace existing files that are newer than their archive copies

       --no-overwrite-dir
              preserve metadata of existing directories

       --overwrite
              overwrite existing files when extracting

       --overwrite-dir
              overwrite metadata of existing directories when extracting (default)

       --recursive-unlink
              empty hierarchies prior to extracting directory

       --remove-files
              remove files after adding them to the archive

       --skip-old-files
              don't replace existing files when extracting, silently skip over them

       -U, --unlink-first
              remove each file prior to extracting over it

       -W, --verify
              attempt to verify the archive after writing it

Select output stream:
       --ignore-command-error ignore exit codes of children

       --no-ignore-command-error
              treat non-zero exit codes of children as error

       -O, --to-stdout
              extract files to standard output

       --to-command=COMMAND
              pipe extracted files to another program

Handling of file attributes:
       --atime-preserve[=METHOD]
              preserve  access  times  on dumped files, either by restoring the times after reading (METHOD='replace'; default) or by not setting the
              times in the first place (METHOD='system')

       --delay-directory-restore
              delay setting modification times and permissions of extracted directories until the end of extraction

       --group=NAME
              force NAME as group for added files

       --mode=CHANGES
              force (symbolic) mode CHANGES for added files

       --mtime=DATE-OR-FILE
              set mtime for added files from DATE-OR-FILE

       -m, --touch
              don't extract file modified time

       --no-delay-directory-restore
              cancel the effect of --delay-directory-restore option

       --no-same-owner
              extract files as yourself (default for ordinary users)

       --no-same-permissions
              apply the user's umask when extracting permissions from the archive (default for ordinary users)

       --numeric-owner
              always use numbers for user/group names

       --owner=NAME
              force NAME as owner for added files

       -p, --preserve-permissions, --same-permissions
              extract information about file permissions (default for superuser)

       --preserve
              same as both -p and -s

       --same-owner
              try extracting files with the same ownership as exists in the archive (default for superuser)

       -s, --preserve-order, --same-order
              sort names to extract to match archive

Handling of extended file attributes:
       --acls Enable the POSIX ACLs support

       --no-acls
              Disable the POSIX ACLs support

       --no-selinux
              Disable the SELinux context support

       --no-xattrs
              Disable extended attributes support

       --selinux
              Enable the SELinux context support

       --xattrs
              Enable extended attributes support

       --xattrs-exclude=MASK
              specify the exclude pattern for xattr keys

       --xattrs-include=MASK
              specify the include pattern for xattr keys

Device selection and switching:
       -f, --file=ARCHIVE
              use archive file or device ARCHIVE

       --force-local
              archive file is local even if it has a colon

       -F, --info-script=NAME, --new-volume-script=NAME
              run script at end of each tape (implies -M)

       -L, --tape-length=NUMBER
              change tape after writing NUMBER x 1024 bytes

       -M, --multi-volume
              create/list/extract multi-volume archive

       --rmt-command=COMMAND
              use given rmt COMMAND instead of rmt
       --rsh-command=COMMAND
              use remote COMMAND instead of rsh

       --volno-file=FILE
              use/update the volume number in FILE

Device blocking:
       -b, --blocking-factor=BLOCKS
              BLOCKS x 512 bytes per record

       -B, --read-full-records
              reblock as we read (for 4.2BSD pipes)

       -i, --ignore-zeros
              ignore zeroed blocks in archive (means EOF)

       --record-size=NUMBER
              NUMBER of bytes per record, multiple of 512

Archive format selection:
       -H, --format=FORMAT
              create archive of the given format

              FORMAT is one of the following:

                     gnu    GNU tar 1.13.x format

                     oldgnu GNU format as per tar <= 1.12

                     pax    POSIX 1003.1-2001 (pax) format

                     posix  same as pax

                     ustar  POSIX 1003.1-1988 (ustar) format

                     v7     old V7 tar format

       --old-archive, --portability
              same as --format=v7

       --pax-option=keyword[[:]=value][,keyword[[:]=value]]...
              control pax keywords

       --posix
              same as --format=posix

       -V, --label=TEXT
              create archive with volume name TEXT; at list/extract time, use TEXT as a globbing pattern for volume name

Compression options:
       -a, --auto-compress
              use archive suffix to determine the compression program

       -I, --use-compress-program=PROG
              filter through PROG (must accept -d)

       -j, --bzip2
              filter the archive through bzip2

       -J, --xz
              filter the archive through xz

       --lzip filter the archive through lzip

       --lzma filter the archive through lzma

       --lzop

       --no-auto-compress
              do not use archive suffix to determine the compression program

       -z, --gzip, --gunzip, --ungzip
              filter the archive through gzip

       -Z, --compress, --uncompress
              filter the archive through compress

       Note: You might need to install external program (lzip/ncompress/lzma...) to use some of these compression options

Local file selection:
       --add-file=FILE
              add given FILE to the archive (useful if its name starts with a dash)

       --backup[=CONTROL]
              backup before removal, choose version CONTROL

       -C, --directory=DIR
              change to directory DIR

       --exclude=PATTERN
              exclude files, given as a PATTERN

       --exclude-backups
              exclude backup and lock files

       --exclude-caches
              exclude contents of directories containing CACHEDIR.TAG, except for the tag file itself

       --exclude-caches-all
              exclude directories containing CACHEDIR.TAG

       --exclude-caches-under exclude everything under directories containing
              CACHEDIR.TAG

       --exclude-tag=FILE
              exclude contents of directories containing FILE, except for FILE itself

       --exclude-tag-all=FILE exclude directories containing FILE

       --exclude-tag-under=FILE
              exclude everything under directories containing FILE

       --exclude-vcs
              exclude version control system directories

       -h, --dereference
              follow symlinks; archive and dump the files they point to

       --hard-dereference
              follow hard links; archive and dump the files they refer to

       -K, --starting-file=MEMBER-NAME
              begin at member MEMBER-NAME in the archive

       --newer-mtime=DATE
              compare date and time when data changed only

       --no-null
              disable the effect of the previous --null option

       --no-recursion
              avoid descending automatically in directories

       --no-unquote
              do not unquote filenames read with -T

       --null                 -T reads null-terminated names, disable -C

       -N, --newer=DATE-OR-FILE, --after-date=DATE-OR-FILE
              only store files newer than DATE-OR-FILE

       --one-file-system
              stay in local file system when creating archive

       -P, --absolute-names
              don't strip leading `/'s from file names

       --recursion
              recurse into directories (default)

       --suffix=STRING
              backup before removal, override usual suffix ('~' unless overridden by environment variable SIMPLE_BACKUP_SUFFIX)

       -T, --files-from=FILE
              get names to extract or create from FILE

       --unquote
              unquote filenames read with -T (default)

       -X, --exclude-from=FILE
              exclude patterns listed in FILE

1.3 解压 + 解包(.tar.gz)

  • 解包: 解包打包文件到指定目录
tar -xvf <dirName/compressedFile>.tar.gz -C <targetDir> # 解出 compressedFile.tar.gz 包中所有文件
      -x, --extract, --get             解压,从归档中【解出】文件
      -c, --create                     create a new archive 压缩,创建一个压缩文件
      -C, --directory=DIR              change to directory DIR 改变至目录 DIR
      -v, --verbose                    详细地列出处理的文件
      -f, --file=ARCHIVE               使用归档文件或 ARCHIVE 设备
      -z, --gzip, --gunzip, --ungzip   通过 gzip 过滤归档
      -j, --bzip2                      filter the archive through bzip2 通过 bzip2 过滤压缩文件

tar -xvf <dirName/compressedFile>.tar -C <targetDir> # 解出 compressedFile.tar 包中所有文件

tar -xjf <dirName/compressedFile>.tar.bz2 -C <targetDir> # 解压 compressedFile.tar.bz2 的文件

1.4 打包 + 压缩(.tar.gz)

  • 打包
    (↓方式1↓ 推荐)
tar -czvf <dirName/fileName>.tar.gz dirName 
    # 对 dirName 文件(夹) 【打包(-c)】,且【压缩(-z)】 为 文件名称为 fileName.tar.gz 的压缩包
      -c, --create                     create a new archive 压缩,创建一个压缩文件
      -v, --verbose                    详细地列出处理的文件
      -f, --file=ARCHIVE               使用归档文件或 ARCHIVE 设备
      -z, --gzip, --gunzip, --ungzip   通过 gzip 过滤归档

例如:tar -czvf /opt/packages/www-server-panel.bak.tar.gz /www/server/panel

(↓方式2↓)

tar -cvf fileName.tar.gz dirName  
    # 对 dirName 文件(夹) 【打包(-c)】,且【压缩(-z)】 为 文件名称为 fileName.tar.gz 的压缩包
      -c, --create                     create a new archive 压缩,创建一个压缩文件
      -v, --verbose                    详细地列出处理的文件
      -f, --file=ARCHIVE               使用归档文件或 ARCHIVE 设备

1.5 打包(.tar)

tar -cvf archive.tar file1.txt file2.txt directory/

这将创建一个名为 archive.tar 的 tar 文件,其中包含 file1.txt、file2.txt 和 directory/。

1.6 解包(.tar)

tar -xvf archive.tar

这将解压名为 archive.tar 的 tar 文件,将其中的文件还原到当前目录。

2 zip / unzip | 打包工具 + 压缩工具

2.1 解压

  • 解压
unzip <dirName/compressedFile>.zip -d <targetDir>

unzip -o /opt/sdc/ue/tomcat/portal.zip -d /opt/sdc/ue/tomcat/webapps

unzip -O CP936 xxx.zip 或者 zip -O CP936 -o xxx.zip 
  CP936 -- GBK: IBM在发明Code Page的时候将GBK编码集放在第936页,所以叫CP936
  UTF8 -- UTF-8(8-bit Unicode Transformation Format)/ 一种针对Unicode的可变长度字符编码

2.2 压缩

  • 压缩
zip -v filename.zip a.c b.c c.c e.c   # 压缩文件

zip -r <dirName/compressedFile>.zip <targetDir> # 压缩指定目录的文件

zip -r filename.zip file1 file2 file3 <targetDir>     # 压缩多个文件或目录

3 gzip / gunzip | 压缩工具

GNU zip
gunzip是gzip的硬链接,请参考gzip

3.1 解压

  • 解压
gunzip -c abc.sql.gz > abc.sql # 解压到指定目录,保留源文件,-c

gzip -dv 压缩文件	# 解压并打印执行过程
  • 案例: demo.gz
$ md5sum.exe demo.gz
9092ea995699a29d6d6e887ae6aaff53 *demo.gz

$ gunzip -c demo.gz > demo.txt

$ md5sum.exe demo.txt
b10a8db164e0754105b7a99be72e3fe5 *demo.txt

"demo.txt"字节数据的16进制表示: 48656c6c6f20576f726c64 ("Hello World")
"demo.gz"字节数据的16进制表示: 1f8b080802319e66000364656d6f2e74787400f348cdc9c95708cf2fca49010056b1174a0b000000

3.2 压缩

  • 压缩
gzip -c 待压缩文件 > 带压缩文件.gz	# 压缩文件并保留源文件
  • 案例: demo.txt
$ cat demo.txt
Hello World

$ md5sum.exe demo.txt
b10a8db164e0754105b7a99be72e3fe5 *demo.txt

$ gzip -c demo.txt > demo.gz

$ md5sum.exe demo.gz
9092ea995699a29d6d6e887ae6aaff53 *demo.gz

4 Z(compress/uncompress) | 压缩工具

  • Z,compress也是一个压缩程序,但是好象使用compress的人不如gzip和bzip2的人多。.Z结尾的文件就是bzip2压缩的结果。与 compress相对的解压程序是uncompress。tar中使用-Z这个参数来调用compress。
# 压缩
compress FileName

# 解压
uncompress FileName.Z

==========

# 解压(结合打包工具TAR)
tar Zxvf FileName.tar.Z

# 压缩(结合打包工具TAR)
tar Zcvf FileName.tar.Z DirName

X 参考文献

  • GZip HomePage & Software
posted @ 2020-09-25 20:22  千千寰宇  阅读(823)  评论(0编辑  收藏  举报