- How to tar a file in Linux using command line
- How to tar a file in Linux using command line
- How to create tar a file in Linux
- How to exclude directories and files when using tar
- How do I view files stored in an archive?
- How do I extracting an archive?
- Conclusion
- Команда Tar в Linux (создание и извлечение архивов)
- Синтаксис команды tar
- Создание архива Tar
- Создание архива Tar Gz
- Создание архива Tar Bz2
- Листинг архивов Tar
- Извлечение архива Tar
- Извлечение архива Tar в другой каталог
- Извлечение архивов Tar Gz и Tar Bz2
- Извлечение определенных файлов из архива Tar
- Извлечение файлов из архива Tar с использованием подстановочного знака
- Добавление файлов в существующий архив Tar
- Удаление файлов из архива Tar
- Выводы
- tar command in Linux with examples
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:
- Open the terminal app in Linux
- Compress an entire directory by running tar -zcvf file.tar.gz /path/to/dir/ command in Linux
- Compress a single file by running tar -zcvf file.tar.gz /path/to/filename command in Linux
- 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
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
Источник
Команда Tar в Linux (создание и извлечение архивов)
Команда tar создает файлы tar путем преобразования группы файлов в архив. Он также может извлекать архивы tar, отображать список файлов, включенных в архив, добавлять дополнительные файлы к существующему архиву и выполнять различные другие операции.
Изначально Tar был разработан для создания архивов для хранения файлов на магнитной ленте, поэтому получил свое название « T ape AR chive».
В этой статье показано, как использовать команду tar для извлечения, перечисления и создания архивов tar на практических примерах и подробных объяснениях наиболее распространенных параметров tar.
Синтаксис команды tar
Существует две версии tar, BSD tar и GNU tar , с некоторыми функциональными отличиями. В большинстве систем Linux по умолчанию предустановлен GNU tar.
Общий синтаксис команды tar следующий:
- OPERATION — Разрешен и обязателен только один аргумент операции. Наиболее часто используемые операции:
- —create ( -c ) — Создать новый tar-архив.
- —extract ( -x ) — Извлечь весь архив или один или несколько файлов из архива.
- —list ( -t ) — Показать список файлов, входящих в архив
- OPTIONS — Наиболее часто используемые операции:
- —verbose ( -v ) — Показать файлы, обрабатываемые командой tar.
- —file=archive=name ( -f archive-name ) — указывает имя файла архива.
- ARCHIVE_NAME — имя архива.
- FILE_NAME(s) — список имен файлов, разделенных пробелами, для извлечения из архива. Если не указан, извлекается весь архив.
При выполнении команд tar вы можете использовать длинную или короткую форму операций и опций tar . Длинные формы более читабельны, а короткие — быстрее печатать. Опции в длинной форме начинаются с двойного тире ( — ). Опции краткой формы имеют префикс с одинарным дефисом ( — ), который можно опустить.
Создание архива Tar
Tar поддерживает широкий спектр программ сжатия, таких как gzip , bzip2 , lzip , lzma , lzop , xz и compress . При создании сжатых tar-архивов принято добавлять суффикс компрессора к имени файла архива. Например, если архив был сжат с помощью gzip , он должен называться archive.tar.gz.
Чтобы создать tar-архив, используйте параметр -c за которым следует -f и имя архива.
Например, чтобы создать архив с именем archive.tar из файлов с именами file1 , file2 , file3 , вы должны выполнить следующую команду:
Вот эквивалентная команда, использующая параметры полной формы:
Вы можете создавать архивы из содержимого одного или нескольких каталогов или файлов. По умолчанию каталоги архивируются рекурсивно, если не указана опция —no-recursion .
В следующем примере будет создан архив с именем user_backup.tar из user_backup.tar /home/user :
Используйте параметр -v если вы хотите увидеть файлы, которые обрабатываются.
Создание архива Tar Gz
Gzip — самый популярный алгоритм сжатия файлов tar. При сжатии tar-архивов с помощью gzip имя архива должно оканчиваться на tar.gz или tgz .
Параметр -z указывает tar сжимать архив с использованием алгоритма gzip мере его создания. Например, чтобы создать архив tar.gz из заданных файлов, вы должны выполнить следующую команду:
Создание архива Tar Bz2
Еще один популярный алгоритм сжатия файлов tar — это bzip2. При использовании bzip2 имя архива должно оканчиваться на tar.bz2 или tbz .
Чтобы сжать архив с помощью алгоритма bzip2 , вызовите tar с параметром -j . Следующая команда создает архив tar.bz2 из указанных файлов:
Листинг архивов Tar
При использовании с параметром —list ( -t ) команда tar выводит список содержимого архива tar без извлечения его.
Команда ниже отобразит содержимое файла archive.tar :
Чтобы получить дополнительную информацию, такую как владелец файла, размер файла, временная метка, используйте параметр —verbose ( -v ):
Извлечение архива Tar
Большинство архивных файлов в Linux заархивированы и сжаты с использованием формата tar или tar.gz. Важно знать, как извлекать эти файлы из командной строки.
Чтобы извлечь tar-архив, используйте параметр —extract ( -x ), за которым следует имя архива:
Также часто добавляют параметр -v для вывода имен извлекаемых файлов.
Извлечение архива Tar в другой каталог
По умолчанию tar извлекает содержимое архива в текущий рабочий каталог . Используйте —directory ( -C ) для извлечения архивных файлов в определенный каталог:
Например, чтобы извлечь содержимое архива в каталог /opt/files , вы можете использовать:
Извлечение архивов Tar Gz и Tar Bz2
При извлечении сжатых архивов, таких как tar.gz или tar.bz2 , вам не нужно указывать параметр распаковки. Команда такая же, как при распаковке tar архива:
Извлечение определенных файлов из архива Tar
Иногда вместо извлечения всего архива вам может потребоваться извлечь из него только несколько файлов.
Чтобы извлечь определенный файл (ы) из архива tar, добавьте разделенный пробелами список имен файлов, которые нужно извлечь, после имени архива:
При извлечении файлов вы должны —list их точные имена, включая путь, как напечатано с помощью —list ( -t ).
Извлечение одного или нескольких каталогов из архива аналогично извлечению файлов:
Если вы попытаетесь извлечь несуществующий файл, отобразится сообщение об ошибке, подобное следующему:
Извлечение файлов из архива Tar с использованием подстановочного знака
Чтобы извлечь файлы из архива на основе шаблона с подстановочными знаками, используйте переключатель —wildcards и —wildcards шаблон в кавычки, чтобы оболочка не интерпретировала его.
Например, чтобы извлечь файлы, имена которых заканчиваются на .js (файлы Javascript), вы можете использовать:
Добавление файлов в существующий архив Tar
Чтобы добавить файлы или каталоги в существующий tar-архив, используйте —append ( -r ).
Например, чтобы добавить файл с именем newfile в archive.tar, вы должны запустить:
Удаление файлов из архива Tar
Используйте операцию —delete для удаления файлов из архива.
В следующем примере показано, как удалить файл file1 из archive.tar:
Выводы
Чаще всего команда tar используется для создания и извлечения архива tar. Чтобы извлечь архив, используйте команду tar -xf за которой следует имя архива, а для создания нового используйте tar -czf за которым следует имя архива, а также файлы и каталоги, которые вы хотите добавить в архив.
Для получения дополнительной информации о команде tar обратитесь к странице документации Gnu tar .
Источник
tar command in Linux with examples
The Linux ‘tar’ stands for tape archive, is used to create Archive and extract the Archive files. tar command in Linux is one of the important command which provides archiving functionality in Linux. We can use Linux tar command to create compressed or uncompressed Archive files and also maintain and modify them.
Syntax:
Options:
-c : Creates Archive
-x : Extract the archive
-f : creates archive with given filename
-t : displays or lists files in archived file
-u : archives and adds to an existing archive file
-v : Displays Verbose Information
-A : Concatenates the archive files
-z : zip, tells tar command that creates tar file using gzip
-j : filter archive tar file using tbzip
-W : Verify a archive file
-r : update or add file or directory in already existed .tar file
What is an Archive file?
An Archive file is a file that is composed of one or more files along with metadata. Archive files are used to collect multiple data files together into a single file for easier portability and storage, or simply to compress files to use less storage space.
Examples:
1. Creating an uncompressed tar Archive using option -cvf : This command creates a tar file called file.tar which is the Archive of all .c files in current directory.
Output :
2. Extracting files from Archive using option -xvf : This command extracts files from Archives.
Output :
3. gzip compression on the tar Archive, using option -z : This command creates a tar file called file.tar.gz which is the Archive of .c files.
4. Extracting a gzip tar Archive *.tar.gz using option -xvzf : This command extracts files from tar archived file.tar.gz files.
5. Creating compressed tar archive file in Linux using option -j : This command compresses and creates archive file less than the size of the gzip. Both compress and decompress takes more time then gzip.
Output :
6. Untar single tar file or specified directory in Linux : This command will Untar a file in current directory or in a specified directory using -C option.
7. Untar multiple .tar, .tar.gz, .tar.tbz file in Linux : This command will extract or untar multiple files from the tar, tar.gz and tar.bz2 archive file. For example the above command will extract “fileA” “fileB” from the archive files.
8. Check size of existing tar, tar.gz, tar.tbz file in Linux : The above command will display the size of archive file in Kilobytes(KB).
9. Update existing tar file in Linux
Output :
10. list the contents and specify the tarfile using option -tf : This command will list the entire list of archived file. We can also list for specific content in a tarfile
Output :
11. Applying pipe to through ‘grep command’ to find what we are looking for : This command will list only for the mentioned text or image in grep from archived file.
12. We can pass a file name as an argument to search a tarfile : This command views the archived files along with their details.
13. Viewing the Archive using option -tvf
Output :
What are wildcards in Linux
Alternatively referred to as a ‘wild character’ or ‘wildcard character’, a wildcard is a symbol used to replace or represent one or more characters. Wildcards are typically either an asterisk (*), which represents one or more characters or question mark (?),which represents a single character.
Example :
14. To search for an image in .png format : This will extract only files with the extension .png from the archive file.tar. The –wildcards option tells tar to interpret wildcards in the name of the files
to be extracted; the filename (*.png) is enclosed in single-quotes to protect the wildcard (*) from being expanded incorrectly by the shell.
Note: In above commands ” * ” is used in place of file name to take all the files present in that particular directory.
?list=PLqM7alHXFySFc4KtwEZTANgmyJm3NqS_L
This article is contributed by Akansh Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Источник