Tar all directories linux

How to tar a file in Linux using command line

How to tar a file in Linux using command line

The procedure is as follows to tar a file in Linux:

  1. Open the terminal app in Linux
  2. Compress an entire directory by running tar -zcvf file.tar.gz /path/to/dir/ command in Linux
  3. Compress a single file by running tar -zcvf file.tar.gz /path/to/filename command in Linux
  4. Compress multiple directories file by running tar -zcvf file.tar.gz dir1 dir2 dir3 command in Linux

How to create tar a file in Linux

Say you want to compress an entire directory named /home/vivek/data/:
$ tar -czvf file.tar.gz /home/vivek/data/
To compress multiple directories and files, execute:
$ tar -czvf file.tar.gz /home/vivek/data/ /home/vivek/pics/ /home/vivek/.accounting.db
One can use bzip2 compression instead of gzip by passing the -j option to the tar command:
$ tar -c j vf file.tar. bz2 /home/vivek/data/
Where,

  • -c : Create a new archive
  • -v : Verbose output
  • -f file.tar.gz : Use archive file
  • -z : Filter the archive through gzip
  • -j : Filter the archive through bzip2

How to exclude directories and files when using tar

You can exclude certain files when creating a tarball. The syntax is:
$ tar -zcvf archive.tar.gz —exclude=’dir1′ —exclude=’regex’ dir1
For example, exclude

/Downloads/ directory:
$ tar -czvf /nfs/backup.tar.gz —exclude=»Downloads» /home/vivek/

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

How do I view files stored in an archive?

Now you have an archive, to list the contents of a tar or tar.gz file using the tar command:
$ tar -ztvf file.tar.gz
$ tar -jtvf file.tar.bz2

How do I extracting an archive?

You can extract an archive or tarball with the tar command. The syntax is:
$ tar -xzvf file.tar.gz
$ tar -xjvf file.tar.bz2
Want to extract the contents of the archive into a specific directory such as /home/vivek/backups/? Try passing the -C DIR option:
$ tar -xzvf my.tar.gz -C /home/vivek/backups/
$ tar -xjvf archive.tar.bz2 -C /tmp/

  • -x : Extract files from an archive
  • -t : List the contents of an archive
  • -v : Verbose output
  • -f file.tar.gz : Use archive file
  • -C DIR : Change to DIR before performing any operations
  • —exclude : Exclude files matching PATTERN/DIR/FILENAME
Читайте также:  Как разархивировать папку с файлами windows

Conclusion

You learned how to tar a file in Linux using tar command. For more info please tar command help page here.

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

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:

Tutorial details
Difficulty level Easy
Root privileges No
Requirements tar
Est. reading time 1 mintue
  1. Create the archive
  2. Compress the archive
  3. Additional operations includes listing, deleting or updating the archive files.

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 source-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/

A note about non gnu/tar command

The above syntax use GNU tar command for compressing and uncompressing tar files. If your system does not use GNU tar, you can still create a compressed tar file, via the following syntax:
tar -cvf — file1 file2 dir3 | gzip > archive.tar.gz

How to use bzip2 compression instead of gzip compression

The syntax is:
tar -jcvf my-compressed.tar.bz2 /path/to/dir1/

  • -j : Compress archive using bzip2 program in Linux or Unix
  • -c : Make archive on Linux
  • -v : Verbose output
  • -f my-compressed.tar.bz2 : Store archive in my-compressed.tar.bz2 file

Conclusion

You learend how to comporess a whole directory in Linux, macOS, *BSD and Unix-like systems using the zip command/tar command. See also:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

See the zip and tar command man page documentation by typing the following man command:
man tar
man zip

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Команда 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. Просмотр содержимого архива

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

tar -tf archive.tar

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.

Источник

How to Tar a Directory

wikiHow is a “wiki,” similar to Wikipedia, which means that many of our articles are co-written by multiple authors. To create this article, 10 people, some anonymous, worked to edit and improve it over time.

This article has been viewed 79,819 times.

The most common way to deliver a batch of files from a Linux system is by using the tar command. When you tar a directory, you can easily roll up a group of files into a single file. This file can then be transferred or stored, or it can be compressed to reduce its size.

  • tar — This invokes the tar archiving program.
  • c — This flag signals the «creation» of the .tar file. It should always come first.
  • v — This indicates that the process is «verbose». This will display a readout of all the files that get added to the .tar file as it is being created. This is an optional flag.
  • f — This flag signifies that the next part will be the new .tar file’s file name. It should always be the last flag.
  • tarName.tar — You can choose any name that you’d like. Just make sure that you include the .tar extension at the end. You can add a path to the file name if you want to create the tarball in a different directory than your current working one.
  • /path/to/directory — Enter in the path of the directory that you want to create the .tar file from. The path is relative to your current working directory. For example, if the full path is

/home/user/Pictures , and you’re currently in the /home directory, you would enter /user/Pictures . Note that all subdirectories will be included as well.

Источник

Читайте также:  Подлинная копия windows не является подлинной
Оцените статью