Меню Рубрики

Tar folder in linux

Compress a folder with tar?

I’m trying to compress a folder ( /var/www/ ) to

/www_backups/$time.tar where $time is the current date.

This is what I have:

I am completely lost and I’ve been at this for hours now. Not sure if -czf is correct. I simply want to copy all of the content in /var/www into a $time.tar file, and I want to maintain the file permissions for all of the files. Can anyone help me out?

2 Answers 2

To tar and gzip a folder, the syntax is:

The — with czf is optional.

If you want to tar the current directory, use . to designate that.

To construct filenames dynamically, use the date utility (look at its man page for the available format options). For example:

This will create a file named something like 20120902-185558.tar.gz .

On Linux, chances are your tar also supports BZip2 compression with the j rather than z option. And possibly others. Check the man page on your local system.

/www_backups/$time.tar /var/www/» Imagine i have a file called test.txt inside /var/www. After making a tar copy of the file, when i extract it it will be placed inside /var/www directories. Does that make sense? I hope it does, kinda hard to explain. I will check for BZip2 support, thanks for the suggestion! – qwerty Sep 2 ’12 at 17:27

Examples for Most Common Compression Algorithms

The question title for this is simply «Compress a folder with tar?» Since this title is very general, but the question and answer are much more specific, and due to the very large number of views this question has attracted, I felt it would be beneficial to add an up-to-date list of examples of both archiving/compressing and extracting/uncompressing, with various commonly used compression algorithms.

These have been tested with Ubuntu 18.04.4. They are very simple for general use, but could easily be integrated into the OP’s more specific question contents using the the techniques in the accepted answer and helpful comments above.

One thing to note for the more general audience is that tar will not add the necessary extensions (like .tar.gz ) automatically — the user has to explicitly add those, as seen in the commands below:

See the tar man page (best to use man tar on your specific machine) for further details. Below I summarize the options used above directly from the man page:

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

-v, —verbose
verbosely list files processed

-z, —gzip
filter the archive through gzip

-j, —bzip2
filter the archive through bzip2

-J, —xz
filter the archive through xz

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

No need to add the — in front of the combined options, or the = sign between the f option and the filename.

I got all this from my recent article, which will be expanded further into a much more comprehensive article as I have time to work on it.

Источник

How to compress and tar a folder in Linux [closed]

Want to improve this question? Update the question so it’s on-topic for Stack Overflow.

Closed 5 months ago .

I am new to Linux, I have a folder called stacey . How can I create a compressed tarball from this?

I can tar the folder with tar -cvzf stacey.tar * . But can I add the 7zip at the same time as so I have a compressed tarball called stacey.tar.gz ?

2 Answers 2

Passing -z on the tar command will gzip the file, so you should name your file stacey.tar.gz (or stacey.tgz ), not stacey.tar :

If you want to 7zip the file (instead of Gzip), remove the -z , keep stacey.tar , and run 7z stacey.tar after the tar command completes:

Or you can use a pipeline to do it in one step:

7zip is more like tar in that it keeps an index of files in the archive. You can actually skip the tar step entirely and just use 7zip:

Источник

How do I Compress a Whole Linux or UNIX Directory?

H ow can I compress a whole directory under a Linux / UNIX using a shell prompt?

It is very easy to compress a Whole Linux/UNIX directory. It is useful to backup files, email all files, or even to send software you have created to friends. Technically, it is called as a compressed archive. GNU tar or BSD tar command is best for this work. It can be use on remote Linux or UNIX server. It does two things for you:[donotprint]

Tutorial details
Difficulty Easy (rss)
Root privileges No
Requirements tar
Time 1m

[/donotprint]

=> Create the archive

=> Compress the archive

=> Additional operations includes listing or updating the archive

How to compress a whole directory in Linux or Unix

You need to use the tar command as follows (syntax of tar command):
tar -zcvf archive-name.tar.gz directory-name
Where,

  • -z : Compress archive using gzip program in Linux or Unix
  • -c : Create archive on Linux
  • -v : Verbose i.e display progress while creating archive
  • -f : Archive File name

For example, say you have a directory called /home/jerry/prog and you would like to compress this directory then you can type tar command as follows:
$ tar -zcvf prog-1-jan-2005.tar.gz /home/jerry/prog
Above command will create an archive file called prog-1-jan-2005.tar.gz in current directory. If you wish to restore your archive then you need to use the following command (it will extract all files in current directory):
$ tar -zxvf prog-1-jan-2005.tar.gz
Where,

  • -x : Extract files from given archive

If you wish to extract files in particular directory, for example in /tmp then you need to use the following command:
$ tar -zxvf prog-1-jan-2005.tar.gz -C /tmp
$ cd /tmp
$ ls —

Compress an entire directory to a single file

To compress directory named /home/vivek/bin/ in to a /tmp/bin-backup.tar.gz type the tar command on Linux:
tar -zcvf /tmp/bin-backup.tar.gz /home/vivek/bin/

You can compress multiple directories too:
tar -zcvf my-compressed.tar.gz /path/to/dir1/ /path/to/dir2/

Источник

How do I tar a directory of files and folders without including the directory itself?

What if I just want to include everything (including any hidden system files) in my_directory, but not the directory itself? I don’t want:

17 Answers 17

should do the job in one line. It works well for hidden files as well. «*» doesn’t expand hidden files by path name expansion at least in bash. Below is my experiment:

Use the -C switch of tar:

The -C my_directory tells tar to change the current directory to my_directory , and then . means «add the entire current directory» (including hidden files and sub-directories).

Make sure you do -C my_directory before you do . or else you’ll get the files in the current directory.

You can also create archive as usual and extract it with:

Have a look at —transform / —xform , it gives you the opportunity to massage the file name as the file is added to the archive:

Transform expression is similar to that of sed , and we can use separators other than / ( , in the above example).
https://www.gnu.org/software/tar/manual/html_section/tar_52.html

With some conditions (archive only files, dirs and symlinks):

Explanation

The below unfortunately includes a parent directory ./ in the archive:

You can move all the files out of that directory by using the —transform configuration option, but that doesn’t get rid of the . directory itself. It becomes increasingly difficult to tame the command.

You could use $(find . ) to add a file list to the command (like in magnus’ answer), but that potentially causes a «file list too long» error. The best way is to combine it with tar’s -T option, like this:

Basically what it does is list all files ( -type f ), links ( -type l ) and subdirectories ( -type d ) under your directory, make all filenames relative using -printf «%P\n» , and then pass that to the tar command (it takes filenames from STDIN using -T — ). The -C option is needed so tar knows where the files with relative names are located. The —no-recursion flag is so that tar doesn’t recurse into folders it is told to archive (causing duplicate files).

If you need to do something special with filenames (filtering, following symlinks etc), the find command is pretty powerful, and you can test it by just removing the tar part of the above command:

For example if you want to filter PDF files, add ! -name ‘*.pdf’

Non-GNU find

The command uses printf (available in GNU find ) which tells find to print its results with relative paths. However, if you don’t have GNU find , this works to make the paths relative (removes parents with sed ):

Источник

Команда tar в Linux

В качестве инструмента для архивации данных в Linux используются разные программы. Например архиватор Zip Linux, приобретший большую популярность из-за совместимости с ОС Windows. Но это не стандартная для системы программа. Поэтому хотелось бы осветить команду tar Linux — встроенный архиватор.

Изначально tar использовалась для архивации данных на ленточных устройствах. Но также она позволяет записывать вывод в файл, и этот способ стал широко применяться в Linux по своему назначению. Здесь будут рассмотрены самые распространенные варианты работы с этой утилитой.

Синтаксис команды tar

Синтаксис команд для создания и распаковки архива практически не отличается (в том числе с утилитами сжатия bzip2 или gzip). Так, чтобы создать новый архив, в терминале используется следующая конструкция:

tar опции архив.tar файлы_для_архивации

Для его распаковки:

tar опции архив.tar

Функции, которые может выполнять команда:

Функция Длинный
формат
Описание
-A —concatenate Присоединить существующий архив к другому
-c —create Создать новый архив
-d —diff
—delete
Проверить различие между архивами
Удалить из существующего архива файл
-r —append Присоединить файлы к концу архива
-t —list Сформировать список содержимого архива
-u —update Обновить архив более новыми файлами с тем же именем
-x —extract Извлечь файлы из архива

При определении каждой функции используются параметры, которые регламентируют выполнение конкретных операций с tar-архивом:

Параметр Длиннный
формат
Описание
-C dir —directory=DIR Сменить директорию перед выполнением операции на dir
-f file —file Вывести результат в файл (или на устройство) file
-j —bzip2 Перенаправить вывод в команду bzip2
-p —same-permissions Сохранить все права доступа к файлу
-v —verbose Выводить подробную информацию процесса
—totals Выводить итоговую информацию завершенного процесса
-z —gzip Перенаправить вывод в команду gzip

А дальше рассмотрим примеры того, как может применяться команда tar Linux.

Как пользоваться tar

1. Создание архива tar

С помощью следующей команды создается архив archive.tar с подробным выводом информации, включающий файлы file1, file2 и file3:

tar —totals —create —verbose —file archive.tar file1 file2 file3

Но длинные опции и параметры можно заменить (при возможности) однобуквенными значениями:

tar —totals -cvf archive.tar file1 file2 file3

2. Просмотр содержимого архива

Следующая команда выводит содержимое архива, не распаковывая его:

3. Распаковка архива tar Linux

Распаковывает архив test.tar с выводом файлов на экран:

tar -xvf archive.tar

Чтобы сделать это в другой каталог, можно воспользоваться параметром -C:

tar -C «Test» -xvf archive.tar

3. Работа со сжатыми архивами

Следует помнить, что tar только создаёт архив, но не сжимает. Для этого используются упомянутые компрессорные утилиты bzip2 и gzip. Файлы, сжатые с их помощью, имеют соответствующие расширения .tar.bz2 и .tar.gz. Чтобы создать сжатый архив с помощью bzip2, введите:

tar -cjvf archive.tar.bz2 file1 file2 file3

Синтаксис для gzip отличается одной буквой в параметрах, и меняется окончание расширения архива:

tar -czvf archive.tar.gz file1 file2 file3

При распаковке tar-архивов с таким расширением следует указывать соответствующую опцию:

tar -C «Test» -xjvf arhive.tar.bz2

tar -xzvf archive.tar.gz

На заметку: архиватор tar — одна из немногих утилит в GNU/Linux, в которой перед использованием однобуквенных параметров, стоящих вместе, можно не ставить знак дефиса.

Выводы

В этой статье была рассмотрена команда tar Linux, которая используется для архивации файлов и поставляется по умолчанию во всех дистрибутивах. В её возможности входит создание и распаковка архива файлов без их сжатия. Для сжатия утилита применяется в связке с популярными компрессорами bzip2 и gzip.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

  • Проблемы с установкой mac os sierra
  • Проблемы с wifi mac os время подключения истекло
  • Проблемы с bootcamp после обновления mac os sierra
  • Проблема с вложениями mail mac os
  • Принцип работы операционной системы mac os