linux命令tar学习笔记

命令简介
tar是linux/unix下的打包、压缩及解压缩工具。利用tar命令,用户可以为某一特定文件创建档案(备份文件),也可以在档案中改变文件,或者向档案中加入新的文件。 tar最初被用来在磁带上创建档案,现在,用户可以在任何设备上创建档案,如软盘。利用tar命令,也可以把一大堆的文件和目录全部打包成一个文件(这才是tar最重要的作用),这对于备份文件或将几个文件组合成为一个文件以便于网络传输是非常有用的。

语法格式

tar [主选项+辅选项] 文件或者目录

使用该命令时,主选项(-c|-r|-t|-u|-x)是必须要有的,它告诉tar要做什么事情,辅选项是辅助使用的,可以选用。

主选项说明:

-c :建立一个压缩文件的参数指令(单词create或者compress的首字母?)。

-r :向压缩档案中追加新的文件。

-t :查看 tarfile 里面的文件。

-u :更新tar压缩档案中的指定文件(u应该是update的缩写)。

-x :解开一个压缩文件的参数指令。

对于主选项而言,需要注意一次只能使用其中一个选项,因为不可能压缩的时候又在解压缩。

辅助选项说明:

-b:该选项是为磁带机设定的。其后跟一数字,用来说明区块的大小,系统预设值为20(20*512 bytes)。

-f:使用档案文件或设备,这个选项通常是必选的。

-k:保存已经存在的文件。例如我们把某个文件还原,在还原的过程中,遇到相同的文件,不会进行覆盖。

-m:在还原文件时,把所有文件的修改时间设定为现在。

-M:创建多卷的档案文件,以便在几个磁盘中存放。

-v:详细报告tar处理的文件信息。如无此选项,tar不报告文件信息。

-w:每一步都要求确认。

-z:用gzip来压缩/解压缩文件,加上该选项后可以将档案文件进行压缩,但还原时也一定要使用该选项进行解压缩。

辅助选项不一定适用所有情况,在某些linux版本或者unix平台下可能无法使用,遇到此种情况可以参阅相应的man手册。

示例1:压缩指定的文件

tar cvf ./c.tar a.txt b.txt

输出:

a a.txt 0 blocks.
a b.txt 0 blocks.

说明
以上命令将a.txt、b.txt打包到当前目录下的c.tar中。看AIX的man手册中有个例子可以不指定tar文件名(tar a.txt b.txt),测试了一下可以正常运行却不知道压缩文件被放到哪里去了。还是使用f参数直接指定压缩文件路径及名称更合适。

示例2:压缩指定目录

tar cvf ./test.tar ./test

输出:


a ./test
a ./test/a.txt 0 blocks.
a ./test/b.txt 0 blocks.
a ./test/c.tar 20 blocks.

说明:
使用相对路径更方便一些,也可以使用绝对路径。

示例3:打包所有的jpg图片


tar -cvf all.tar *.jpg

示例4:将所有的gif图片追加到all.tar中

# tar -rf all.tar *.gif

说明:
这条命令是将所有.gif的文件增加到all.tar的包里面去。-r是表示增加文件的意思。

示例5:更新tar压缩档案中的指定文件

# tar -uf all.tar logo.gif

这条命令是更新原来tar包all.tar中logo.gif文件,-u是表示更新文件的意思。

示例6:查看压缩文件中的内容


tar tf ./test.tar

输出:


a.txt
b.txt

示例7:解压文档


tar -xvf ./test.tar

输出:


x ./test
x ./test/a.txt, 0 bytes, 0 media blocks.
x ./test/b.txt, 0 bytes, 0 media blocks.
x ./test/c.tar, 10240 bytes, 20 media blocks.

以下的例子随处可见,最初大概来源于鸟哥的私房菜,copy过来作为参考。

范例一:将整个 /etc 目录下的文件全部打包成为 /tmp/etc.tar
[root@linux ~]# tar -cvf /tmp/etc.tar /etc <==仅打包,不压缩! [root@linux ~]# tar -zcvf /tmp/etc.tar.gz /etc <==打包后,以 gzip 压缩 [root@linux ~]# tar -jcvf /tmp/etc.tar.bz2 /etc <==打包后,以 bzip2 压缩 # 特别注意,在参数 f 之后的文件档名是自己取的,我们习惯上都用 .tar 来作为辨识。 # 如果加 z 参数,则以 .tar.gz 或 .tgz 来代表 gzip 压缩过的 tar file ~ # 如果加 j 参数,则以 .tar.bz2 来作为附档名啊~ # 上述指令在执行的时候,会显示一个警告讯息: # 『tar: Removing leading `/' from member names』那是关於绝对路径的特殊设定。 范例二:查阅上述 /tmp/etc.tar.gz 文件内有哪些文件?
[root@linux ~]# tar -ztvf /tmp/etc.tar.gz
# 由於我们使用 gzip 压缩,所以要查阅该 tar file 内的文件时,
# 就得要加上 z 这个参数了!这很重要的!

范例三:将 /tmp/etc.tar.gz 文件解压缩在 /usr/local/src 底下
[root@linux ~]# cd /usr/local/src
[root@linux src]# tar -zxvf /tmp/etc.tar.gz
# 在预设的情况下,我们可以将压缩档在任何地方解开的!以这个范例来说,
# 我先将工作目录变换到 /usr/local/src 底下,并且解开 /tmp/etc.tar.gz ,
# 则解开的目录会在 /usr/local/src/etc 呢!另外,如果您进入 /usr/local/src/etc
# 则会发现,该目录下的文件属性与 /etc/ 可能会有所不同喔!

范例四:在 /tmp 底下,我只想要将 /tmp/etc.tar.gz 内的 etc/passwd 解开而已
[root@linux ~]# cd /tmp
[root@linux tmp]# tar -zxvf /tmp/etc.tar.gz etc/passwd
# 我可以透过 tar -ztvf 来查阅 tarfile 内的文件名称,如果单只要一个文件,
# 就可以透过这个方式来下达!注意到! etc.tar.gz 内的根目录 / 是被拿掉了!

范例五:将 /etc/ 内的所有文件备份下来,并且保存其权限!
[root@linux ~]# tar -zxvpf /tmp/etc.tar.gz /etc
# 这个 -p 的属性是很重要的,尤其是当您要保留原本文件的属性时!

范例六:在 /home 当中,比 2005/06/01 新的文件才备份
[root@linux ~]# tar -N ‘2005/06/01’ -zcvf home.tar.gz /home

范例七:我要备份 /home, /etc ,但不要 /home/dmtsai
[root@linux ~]# tar –exclude /home/dmtsai -zcvf myfile.tar.gz /home/* /etc

范例八:将 /etc/ 打包后直接解开在 /tmp 底下,而不产生文件!

[root@linux ~]# cd /tmp
[root@linux tmp]# tar -cvf – /etc | tar -xvf –
# 这个动作有点像是 cp -r /etc /tmp 啦~依旧是有其有用途的!
# 要注意的地方在於输出档变成 – 而输入档也变成 – ,又有一个 | 存在~
# 这分别代表 standard output, standard input 与管线命令啦!
# 这部分我们会在 Bash shell 时,再次提到这个指令跟大家再解释啰!


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

AIX的tar命令帮助文档。

tar Command

Purpose

Manipulates archives.

Syntax

X/Open Standards:

tar {-c|-r|-t|-u|-x} [-B] [ -d ] [ -E ] [ -F ] [-h ] [ -i ] [ -l ] [ -m ] [ -o ] [ -p ] [ -s ] [ -U ] [ -v ] [ -w]
* [-Number] [-f Archive] [-b Blocks]
* [-S [Feet] [Feet @Density] [Blocksb]] [-L InputList] [-X ExcludeList]
* [-N Blocks] [-R] [-D] [-C Directory] File | Directory …

Berkeley Standards:

tar {c |r|t|u|x} [bBdDEfFhilLXmNopRsSUvw[0-9] ]
* [ Blocks ] [ Archive ] [ InputList ] [ ExcludeFile ]
* [ [ Feet ] | [ Feet@Density ] | [ Blocksb ] ] Directory | File …

Description
Attention: Because of limitations on header block space in the tar command, user numbers (UIDs), and group identification
numbers (GIDs) larger than 65,535 will be corrupted when restored to certain systems. The size constraint affects only the
ownership and permissions causing no damage to the data. Corruption of the ownership occurs on the following systems:
* Those that do not use uname and gname fields to check ownership.
* Those that do not have the same user and group IDs as the archiving system. Notes:
1 The ustar header format allows for file sizes to be as large as 8 GB. Therefore, the tar command is enabled to archive
files of up to 8 GB in size.
2 tar does not preserve the sparse nature of any file that is sparsely allocated. Any file that was originally sparse
before the restoration will have all space allocated within the filesystem for the size of the file.

The tar command manipulates archives by writing files to, or retrieving files from an archive storage medium. The files
used by the tar command are represented by the File parameter. If the File parameter refers to a directory, then that
directory and recursively all files and directories within it are referenced as well.

The tar command looks for archives on the default device (usually tape), unless you specify another device with the -f
Archive flag. When specifying path names that are greater than 100 characters for the United States Tape Archiver (USTAR)
format, remember that the path name is composed of a prefix buffer, a / (slash), and a name buffer.

The prefix buffer can be a maximum of 155 bytes and the name buffer can hold a maximum of 100 bytes. If the path name
cannot be split into these two parts by a slash, it cannot be archived. This limitation is due to the structure of the tar
archive headers, and must be maintained for compliance with standards and backwards compatibility. In addition, the length
of a destination for a hard or symbolic link ( the ‘link name’) cannot exceed 100 bytes.

When writing to an archive, the tar command uses a temporary file (the /tmp/tar* file) and maintains in memory a table of
files with several links. You receive an error message if the tar command cannot create the temporary file, or if there is
not enough memory available to hold the link tables.

Two groups of flags exist for the tar command: the required flags and the optional flags. The required flags control the
actions of the tar command and include the -c, -r, -t, -u, and -x flags. At least one required flag must be selected for
the tar command to function. Having selected a required flag, you can select an optional flag but none are necessary to
control the tar command. Notes:
1 When the storage device is an ordinary file or a block special file, the -u and -r flags backspace. However, raw
magnetic tape devices do not support backspacing. So when the storage device is a raw magnetic tape, the -u and -r
flags rewind the tape, open it, and then read it again.

2 Records are one block long on block magnetic tape, but they are typically less than half as dense on raw magnetic
tape. As a result, although a blocked raw tape must be read twice, the total amount of tape motion is less than when
reading one-block records from a block magnetic tape once.
3 The structure of a streaming tape device does not support the addition of information at the end of a tape.
Consequently when the storage device is a streaming tape, the -u and -r flags are not valid options. An attempt to use
these flags results in the following error message:

tar: Update and Replace options not valid for a
streaming tape drive.
4 No recovery exists from tape errors.
5 The performance of the tar command to the IBM 9348 Magnetic Tape Unit Model 12 can be improved by changing the default
block size. To change the block size, enter the following at the command line:

chdev -1 -a block_size=32k

For more information on using tape devices see the rmt special file.

Flags

Flags for the tar command are in two groups, the required and the optional. You must supply at least one required flag to
control the tar command.
Required Flags
-c
Creates a new archive and writes the files specified by one or more File parameters to the beginning of the archive.
-r
Writes the files specified by one or more File parameters to the end of the archive. This flag is not valid for any
tape devices because such devices do not support the addition of information at the end of a tape.
-t
Lists the files in the order in which they appear in the archive. Files can be listed more than once.
-u
Adds the files specified by one or more File parameters to the end of the archive only if the files are not in the
archive already, or if they have been modified since being written to the archive. The -u flag is not valid for any
tape devices because such devices do not support the addition of information at the end of a tape.
-U
Allows archival and extraction of Extended Attributes. The Extended Attributes include Access control list (ACL) also.
-x
Extracts the files specified by one or more File parameters from the archive. If the File parameter refers to a
directory, the tar command recursively extracts that directory from the archive. If you do not specify the File
parameter, the tar command extracts all of the files from the archive. When an archive contains multiple copies of the
same file, the last copy extracted overwrites all previously extracted copies. If the file being extracted does not
already exist on the system, the file is created. If you have the proper permissions, the tar command restores all
files and directories with the same owner and group IDs as they have on the tape. If you do not have the proper
permissions, the files and directories are restored with your owner and group IDs. It is not possible to ask for any
occurrence of a file other than the last.
Optional Flags
-B
Forces input and output blocking to 20 blocks per record. With this option, the tar command can work across
communications channels where blocking may not be maintained.
-b Blocks
Specifies the number of 512 bytes blocks per record. Both the default and the maximum is 20, which is appropriate for
tape records. Due to the size of interrecord gaps, tapes written with large blocking factors can hold much more data
than tapes with only one block per record.

The block size is determined automatically when tapes are read (the -x or -t function flags). When archives are
updated with the -u and -r functions, the existing record size is used. The tar command writes archives using the
specified value of the Blocks parameter only when creating new archives with the -c flag.

For output to ordinary files with the -f flag, you can save disk space by using a blocking factor that matches the
size of disk blocks (for example, the -b4 flag for 2048-byte disk blocks).

-C Directory
Causes the tar command to perform a chdir subroutine to the directory specified by the Directory variable. Using the
-C flag allows multiple directories not related by a close common parent to be archived, using short relative path
names. For example, to archive files from the /usr/include and /etc directories, you might use the following command:
tar c -C /usr/include File1 File2 -C /etc File3 File4

The -CDirectory flag must appear after all other flags and can appear in the list of file names given.
-D
Suppress recursive processing when directories are specified.
-d
Makes separate entries for block files, special character files, and first-in-first-out (FIFO) piped processes.
Normally, the tar command will not archive these special files. When writing to an archive with the -d flag, the tar
command makes it possible to restore empty directories, special files, and first-in-first-out (FIFO) piped processes
with the -x flag. Note: Although anyone can archive special files, only a user with root user authority can extract
them from an archive (FIFO can also be extracted by non-root users).
-E
Avoids truncation of the long user and group names during addition of files to new or existing archive.
-F
Checks the file type before archiving. Source Code Control Systems (SCCS), Revision Control Systems (RCS), files named
core, errs, a.out, and files ending in .o (dot o) are not archived.
-f Archive
Uses the Archive variable as the archive to be read or written. When this flag is not specified, the tar command uses
a system-dependent default file name of the form /dev/rmt0. If the Archive variable specified is – (minus sign), the
tar command writes to standard output or reads from standard input. If you write to standard output, the -c flag must
be used.
-h
Forces the tar command to follow symbolic links as if they were normal files or directories. Normally, the tar command
does not follow symbolic links.
-i
Ignores header checksum errors. The tar command writes a file header containing a checksum for each file in the
archive. When this flag is not specified, the system verifies the contents of the header blocks by recomputing the
checksum and stops with a directory checksum error when a mismatch occurs. When this flag is specified, the tar
command logs the error and then scans forward until it finds a valid header block. This permits restoring files from
later volumes of a multi-volume archive without reading earlier volumes.
-L InputList
The Inputlist argument to the -L option should always be the name of the file that lists the files and directories
that need to be archived or extracted.
-l
Writes an error message to standard output for each file with a link count greater than 1 whose corresponding links
were not also archived. For example, if file1 and file2 are hard-linked together and only file1 is placed on the
archive, then the -l flag will issue an error message. Error messages are not displayed if the -l flag is not
specified.
-m
Uses the time of extraction as the modification time. The default is to preserve the modification time of the files.
-N Blocks
Allows the tar command to use very large clusters of blocks when it deals with streaming tape archives. Note however,
that on input, the tar command cannot automatically determine the block size of tapes with very long block sizes
created with this flag. In the absence of a -N Blocks flag, the largest block size that the tar command can
automatically determine is 20 blocks.
-o
Provides backwards compatibility with older versions (non-AIX) of the tar command. When this flag is used for reading,
it causes the extracted file to take on the User and Group ID (UID and GID) of the user running the program, rather
than those on the archive. This is the default behavior for the ordinary user.
-p
Restores fields to their original modes, ignoring the present umask. The setuid, setgid, and tacky bit permissions are
also restored to the user with root user authority. This flag restores files to their original mode but does not
restore directories to their original mode.
-R

Use recursion when directories are specified. Ignored when used with the-D option.
-s
Tries to create a symbolic link If the tar command is unsuccessful in its attempt to link (regular link) two files
with the -s flag.
-SBlocksb, -S Feet, -S Feet@Density
Specifies the number of 512KB blocks per volume (first format), independent of the tape blocking factor. You can also
specify the size of the tape in feet by using the second form, in which case the tar command assumes a default Density
variable. The third form allows you to specify both tape length and density. Feet are assumed to be 11 inches long to
be conservative. This flag lets you deal more easily with multivolume tape archives, where the tar command must be
able to determine how many blocks fit on each volume. Notes:
1 Tape drives vary in density capabilities. The Density variable calculates the amount of data a system can fit
on a tape.
2 When using 1/4-inch tape devices, be sure to take into account the number of tracks on the tape device when
specifying the value for the Feet variable. For example, a 4-track,1/4-inch tape drive with a 600-foot tape and
a density of 8000 bpi can be specified using the -S Feet@Density flag as follows:

-S 2400@8000

where 600 feet multiplied by 4 tracks equals 2400 feet.
-U
Archives or restores named extended attributes and ACLs. When listing, this option will display the names of any named
extended attributes and the type of any ACLs associated with each file that are part of the archive image.
-v
Lists the name of each file as it is processed. With the -t flag, -v gives more information about the tape entries,
including file sizes, times of last modification, User Number (UID), Group Number (GID), and permissions.
-w
Displays the action to be taken, followed by the file name, and then waits for user confirmation. If the response is
affirmative, the action is performed. If the response is not affirmative, the file is ignored.
-Number
Uses the /dev/rmtNumber file instead of the default. For example, the -2 flag is the same as the -f/dev/rmt2 file.
-X ExcludeList
Excludes the file names or directories given in the ExcludeList from the tar archive being created, extracted or
listed. The ExcludeList shall contain only one filename or directory per line which are to be excluded from the tar
archive being created, extracted from or listed. The -X option can be specified multiple times and it takes precedence
over all other options.

Exit Status

This command returns the following exit values:
0
Successful completion.
>0
An error occurred.

Examples
1 To write the file1 and file2 files to a new archive on the default tape drive, enter: tar -c file1 file2

2 To extract all files in the /tmp directory from the archive file on the /dev/rmt2 tape device and use the time of
extraction as the modification time, enter:

tar -xm -f/dev/rmt2 /tmp
3 To create a new archive file that contains the file1 file and pass the archive file to the dd command to be written to
the /dev/rmt1 device, enter:

tar -cvf – file1 | dd of=/dev/rmt1 conv=sync
4 To display the names of the files in the out.tar disk archive file on the current directory, enter:

tar -vtf out.tar

5 To expand the compressed tar archive file, fil.tar.z, pass the file to the tar command, and extract all files from the
expanded tar archive file, enter:

zcat fil.tar.Z | tar -xvf –
6 To archive the contents of /usr/include and /usr/bin files using short relative path names, enter:

cd /usr
tar -cvf/dev/rmt0 -C./include . -C ../bin .

Note: When specifying multiple instances of the -C flag with relative path names, the user must take the previous -C
flag request into account.
7 To archive to an 8-mm device when using the -S flag, enter:

tar -cvf /dev/rmt0 -S 4800000b /usr

Note: When archiving to an 8-mm device, the -S Feet and -S Feet@Density flags are not recommended, since the 8-mm
device does not use the concept of density when writing to a tape.
8 To archive a list of all C files that is listed in the file through the InputList argument of the -L option, enter:

tar -cvf fl.tar -L fl_list
Where fl_list is a file consisting a list of all .c files in it. This can be obtained as follows:

ls *.c > fl_list
9 To archive a list of all C files by setting a variable using the -L option, enter:

ls *.c > fl_list
fl=fl_list
tar -cvf var.tar -L $fl
10 To avoid the truncation of long user or group names during creation of the archive, enter:

tar -cvEf file.tar file
11 To create a new archive file that contains the file1 file with ACL and EA, enter:

tar -cvUf /tmp/tar.ar file1

Berkeley Options

The following are examples of the Berkeley options using the tar command: Note: With Berkeley options the arguments to the
flags should be given in exact order in which the flags are given below. For example:

tar cvfbL test.tar 20 infile
where test.tar is archive tar file, 20 is number of blocks, and infile is Inputlist for the archive.
1 To archive all directories and complete filenames listed in input list file infile into ar.tar, enter :

tar cvfL ar.tar infile
Where infile contains the pathnames of files that are to be archived.
2 To archive files within directories listed in the input list file infile into ar.tar, enter:

tar cvRfL ar.tar infile
3 To extract directories and complete files specified in the input list file infile from an archive named ar.tar, enter:

tar xvfL ar.tar infile
4 To extract files from within directories and complete files specified in the input list file infile from an archive
named ar.tar, enter:

tar xvRfL ar.tar infile

Files

/dev/rmt0
Specifies the default tape device.
/bin/tar
Specifies the symbolic link to the tar command.
/usr/bin/tar
Contains the tar command.
/tmp/tar*
Specifies a temporary file. Note: In AIX 3.2, the entire /bin directory is a symbolic link to /usr/bin.

Related Information

The cat command, dd command, pax command.

The rmt special file.

File systems in Operating system and device management explains file system types, management, structure, and maintenance.

Directory Overview in Operating system and device management explains working with directories and path names.

Files in Operating system and device management provides information on working with files.

此条目发表在lnmpa分类目录,贴了, 标签。将固定链接加入收藏夹。

linux命令tar学习笔记》有1条回应

  1. darkmi说:

    复习一下。

发表评论

您的电子邮箱地址不会被公开。

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据