Linux tar исключить директорию

Linux tar исключить директорию

To avoid operating on files whose names match a particular pattern, use the ‘ —exclude ’ or ‘ —exclude-from ’ options.

Causes tar to ignore files that match the pattern .

The ‘ —exclude= pattern ’ option prevents any file or member whose name matches the shell wildcard ( pattern ) from being operated on. For example, to create an archive with all the contents of the directory ‘src’ except for files whose names end in ‘.o’, use the command ‘ tar -cf src.tar —exclude=’*.o’ src ’.

You may give multiple ‘ —exclude ’ options.

‘ —exclude-from= file ’ ‘ -X file ’

Causes tar to ignore files that match the patterns listed in file .

Use the ‘ —exclude-from ’ option to read a list of patterns, one per line, from file ; tar will ignore files matching those patterns. Thus if tar is called as ‘ tar -c -X foo . ’ and the file ‘foo’ contains a single line ‘*.o’, no files whose names end in ‘.o’ will be added to the archive.

Notice, that lines from file are read verbatim. One of the frequent errors is leaving some extra whitespace after a file name, which is difficult to catch using text editors.

However, empty lines are OK.

When archiving directories that are under some version control system (VCS), it is often convenient to read exclusion patterns from this VCS’ ignore files (e.g. ‘.cvsignore’, ‘.gitignore’, etc.) The following options provide such possibility:

Before archiving a directory, see if it contains any of the following files: ‘cvsignore’, ‘.gitignore’, ‘.bzrignore’, or ‘.hgignore’. If so, read ignore patterns from these files.

The patterns are treated much as the corresponding VCS would treat them, i.e.:

Contains shell-style globbing patterns that apply only to the directory where this file resides. No comments are allowed in the file. Empty lines are ignored.

Contains shell-style globbing patterns. Applies to the directory where ‘.gitfile’ is located and all its subdirectories.

Any line beginning with a ‘ # ’ is a comment. Backslash escapes the comment character.

Contains shell globbing-patterns and regular expressions (if prefixed with ‘ RE: ’(16). Patterns affect the directory and all its subdirectories.

Any line beginning with a ‘ # ’ is a comment.

Contains posix regular expressions(17). The line ‘ syntax: glob ’ switches to shell globbing patterns. The line ‘ syntax: regexp ’ switches back. Comments begin with a ‘ # ’. Patterns affect the directory and all its subdirectories.

Before dumping a directory, tar checks if it contains file . If so, exclusion patterns are read from this file. The patterns affect only the directory itself.

Читайте также:  Postgresql for kali linux

Same as ‘ —exclude-ignore ’, except that the patterns read affect both the directory where file resides and all its subdirectories.

Exclude files and directories used by following version control systems: ‘ CVS ’, ‘ RCS ’, ‘ SCCS ’, ‘ SVN ’, ‘ Arch ’, ‘ Bazaar ’, ‘ Mercurial ’, and ‘ Darcs ’.

As of version 1.34, the following files are excluded:

  • CVS/’, and everything under it
  • RCS/’, and everything under it
  • SCCS/’, and everything under it
  • .git/’, and everything under it
  • .gitignore
  • .gitmodules
  • .gitattributes
  • .cvsignore
  • .svn/’, and everything under it
  • .arch-ids/’, and everything under it
  • /’, and everything under it
  • =RELEASE-ID
  • =meta-update
  • =update
  • .bzr
  • .bzrignore
  • .bzrtags
  • .hg
  • .hgignore
  • .hgrags
  • _darcs

Exclude backup and lock files. This option causes exclusion of files that match the following shell globbing patterns:

When creating an archive, the ‘ —exclude-caches ’ option family causes tar to exclude all directories that contain a cache directory tag. A cache directory tag is a short file with the well-known name ‘CACHEDIR.TAG’ and having a standard header specified in http://www.brynosaurus.com/cachedir/spec.html. Various applications write cache directory tags into directories they use to hold regenerable, non-precious data, so that such data can be more easily excluded from backups.

There are three ‘ exclude-caches ’ options, each providing a different exclusion semantics:

Do not archive the contents of the directory, but archive the directory itself and the ‘CACHEDIR.TAG’ file.

Do not archive the contents of the directory, nor the ‘CACHEDIR.TAG’ file, archive only the directory itself.

Omit directories containing ‘CACHEDIR.TAG’ file entirely.

Another option family, ‘ —exclude-tag ’, provides a generalization of this concept. It takes a single argument, a file name to look for. Any directory that contains this file will be excluded from the dump. Similarly to ‘ exclude-caches ’, there are three options in this option family:

Do not dump the contents of the directory, but dump the directory itself and the file .

Do not dump the contents of the directory, nor the file , archive only the directory itself.

Omit directories containing file file entirely.

Multiple ‘ —exclude-tag* ’ options can be given.

For example, given this directory:

$ find dir dir dir/blues dir/jazz dir/folk dir/folk/tagfile dir/folk/sanjuan dir/folk/trote

The ‘ —exclude-tag ’ will produce the following:

$ tar -cf archive.tar --exclude-tag=tagfile -v dir dir/ dir/blues dir/jazz dir/folk/ tar: dir/folk/: contains a cache directory tag tagfile; contents not dumped dir/folk/tagfile

Both the ‘dir/folk’ directory and its tagfile are preserved in the archive, however the rest of files in this directory are not.

Now, using the ‘ —exclude-tag-under ’ option will exclude ‘tagfile’ from the dump, while still preserving the directory itself, as shown in this example:

$ tar -cf archive.tar --exclude-tag-under=tagfile -v dir dir/ dir/blues dir/jazz dir/folk/ ./tar: dir/folk/: contains a cache directory tag tagfile; contents not dumped

Finally, using ‘ —exclude-tag-all ’ omits the ‘dir/folk’ directory entirely:

$ tar -cf archive.tar --exclude-tag-all=tagfile -v dir dir/ dir/blues dir/jazz ./tar: dir/folk/: contains a cache directory tag tagfile; directory not dumped

This document was generated on March 24, 2021 using texi2html 5.0.

Читайте также:  Кто против linux mint

Источник

Создание и распаковка tar архивов в Linux

Tar — архивы один из наиболее распространённых способов хранения данных в Linux системах. Но tar не сжимает данные в архиве. Tar всего лишь упаковывает файлы. Для сжатия tar умеет работать с утилитами bzip2 или gzip.

Правильнее называть «tarball» (тарболл, «tar» мяч). По сути tar формат — это объединение нескольких файлов в один. Попробуйте объединить несколько текстовых файлов в один tarball и открыть его текстовым редактором. Вы увидите что это лишь большой текстовый файл, в котором перечислено содержимое входящих в него файлов с указанием их путей текстом.

Создать архив из папки

Предположим, что необходимо создать tar архив из папки и использовать при этом сжатие. Чтобы создать архив tar с gzip сжатием, нужно выполнить команду:

tar -zcf /root/files.tar.gz /home/folder/

При выполнении этой команды из содержимого папки /home/folder/ будет создан архив по адресу /root/files.tar.gz . Если указать относительный путь, то файл создастся в той папке, где открыт терминал.

В конце команды передаётся директория, которую надо архивировать. В примере стоит абсолютный путь к этой папке. В таком случае в архиве tar будет находится все родительские папки т.е. при открытии архива там будет папка /home/ и внутри неё папка /folder/. Но если абсолютный путь заменить относительным, то будет только /folder/.

В названии файла «files.tar.gz» можно указать любое расширение. Но для сжатых тарболлов лучше писать именно так. То есть сначала указывать то что это «tar», а потом писать «gz».

Разберём пример по частям. Команда tar в примере выше имеет три ключа:

  • z — архивирует с gzip компрессией. Если нужно использовать bzip2, надо заменить ключ «z» на «j».
  • c — без этого ключа архив не создастся.
  • f — вывод информация в файл. Без этого ключа tar будет выдавать результат на stdout при упаковке и пытаться читать архив с stdin при распаковке.

Исключить папки и файлы при создании архива

Иногда нужно исключить некоторые подпапки при создании архива. К примеру, если надо создать архив из папки /home/, но в него не должны попасть содержания папок /cache/ и /trash/. Тогда необходимо использовать ключ exclude:

tar -zcf /root/files.tar.gz /home/ --exclude=

Символы звёздочек в exclude означают либой набор символов. То есть выполнять эту команду без звёздочек в начале путей, то необходимо прописывать полный путь к папке, которую надо исключить.

В конце значений explude тоже стоят звёздочки, чтобы удалялись не сами папки, а их содержимое (все дочерние файлы и папки).

При выполнении такой команды в архив не попадут файлы из папок:

/home/cache/ /home/folder/cache/ /home/folder/subfolder/cache/

Обратите внимание на то, что внутри фигурных скобок explude нет пробелов . Если поставить пробел до/после запятой или до/после фигурной скобки, то исключение не сработает.

Разархивировать

Чтобы распаковать содержимое tar архива в ту же папку, в которой он находится, перейдите в папку с ним и введите:

Ключ x указывает на распаковку архива. Ключ f обязателен, как и при создании архива.

Если требуется распаковать архив в определённую папку, то путь к ней можно указать после ключа C:

tar -xf files.tar.gz -C /home/folder/

Источник

[Linux] : How to exclude directory when using “tar” shell command

In day-to-day activities administrators needs to perform regular backups on their Linux servers. Being myself an administrator, i would recommended “tar”, the simple and the best tool. Backup doesn’t mean all the files and folders need to be backed up ! Sometimes we may have to exclude directories like template cache, log files, cache, temporarily created files, gallery directory etc., So in this article, we will see how to exclude certain directories and certain patterns even !

Читайте также:  Mounting vhd on linux

1. tar –exclude “directory”

Note: When excluding directories, make sure NOT to use the trailing slash(/) at the end of the directory name.

I have wasted much time in exploring this. So requesting you to not to waste time and follow the good procedure to get the work done soon.

Bad Practice :

tar -cvf backup.tar --exclude="public_html/template/cache/" public_html/

Good Practice :

tar -cvf backup.tar --exclude="public_html/template/cache" public_html/

2. tar –exclude Multiple directories

To exclude multiple directories you can either provide directories separately or by listing each directory seperated by comma and encased in .

Method 1 :

tar -cvf backup.tar --exclude="public_html/template/cache" --exclude="public_html/images" public_html/

Method 2 :

tar -cvf backup.tar --exclude= public_html/

3. tar –exclude directories from a File

List all the directories to be excluded into a file and use this list to exclude directories during tar.

Method 1 :

tar -cvf backup.tar -X exclude_directory.txt public_html/

Method 2 :

tar -cvf backup.tar --exclude-from=exclude_directory.txt public_html/

exclude_directory.txt Contains :

public_html/template/cache public_html/images

4. tar –exclude certain patterns

Sometimes we might find multiple pattern in different folders and we would not be interested only on that pattern. So here we see how to exclude particular pattern.

To exclude directory with particluar pattern :

tar -cvf backup.tar --exclude="log" --exclude="cache" public_heml/

To exclude files with patterns containing preceding and trailing characters :

tar -cvf backup.tar --exclude="*.log" --exclude="cache*" public_heml/

Was this article helpful?

About The Author

Author Profile

Ramya Santhosh

is a Web Designer and content creator. A freelance writer on latest trends in technology, gadget reviews, How to’s and many more.

  • How to shrink a qcow2 Windows VM image on Linux
  • [Linux]: How to Change Hostname on CentOS/RHEL – 7/8
  • No such file or directory c++ Error [CentOS]
  • How to configure Open vSwitch bridge for OpenStack
  • Too many connections for neutron-db-manage [MySQL]
  • How to manually install higher version of PIP for Python v2.7

Comments Leave a Comment

It took me a week off and on to figure out why exclude option wasn’t working. I wanted to exclude all the hidden files and directories from being included in the archive. I generated the file exclude with the ls -a | egrep “^\.” > exclude (list all the files & directories including hidden files, then keep those that start with a . and save results in the exclude file). When I used -X exclude with tar nothing was backed up. Finally, I took a real look at exclude and the first line was just a . The light went off, I had just told tar to exclude the current directory, so no backup. Should have use ls -A (not -a) when I generated exclude to not include . and .. in the output. Live and learn!

Best explanation I read online, simple and definitely works, at least for me :), advise to whose who read this “READ THE ADVICE ABOVE” Thanks a million and keep up the good help

Источник

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