Linux what to do with tar gz

Использование tar в Linux и FreeBSD для работы с архивами

Утилита командной строки tar используется для работы с архивами в операционных системах на базе UNIX. С ее помощью можно архивировать данные и оптимизировать использование дискового пространства.

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

Создать

Создание выполняется с ключом c. Синтаксис следующий:

tar -czvf archive.tar.gz /home/dmosk

* в данном примере будет создан архив archive.tar.gz домашней директории пользователя (/home/dmosk)
** где z — сжать архив в gzip (без этого параметра, tar не сжимает, а создает так называемый тарбол); c — ключ на создание архива; v — verbose режим, то есть с выводом на экран процесса (очень удобно для наблюдением за ходом работы, но в скриптах можно упустить); f — использовать файл (обязательно указываем, так как в большей степени работаем именно с файлами).

Распаковать

Распаковка выполняется с ключом x с синтаксисом:

tar -xvf archive.tar.gz

Примеры

Распаковка .gz файла:

tar -xvf archive.tar.gz

* при возникновении ошибки This does not look like a tar archive, можно воспользоваться командой gzip -d archive.tar.gz.

tar -xvjf archive.tar.bz2

* ключ j отвечает за работу с bz2.

Если система ругается на bzip2, значит нужно его установить:

yum install bzip2

apt-get install bzip2

pkg install bzip2

* соответственно, для CentOS (RPM based), Ubuntu (deb based), FreeBSD (BSD based).

Если видим ошибку tar: Unrecognized archive format, воспользуемся следующей командой:

bzip2 -d archive.tar.bz2

tar -xvzf archive.tar.gzip

* ключ z отвечает за работу с gzip.

Распаковывается, как gzip:

tar -xvzf archive.tgz

Распаковать в определенную папку

tar -C /home/user -xvf archive.tar.gz

* ключ -C используется для указания папки, куда необходимо распаковать файлы из архива.

Распаковка без вложенной папки

Такой способ можно использовать для распаковки в заранее подготовленный каталог. Будет некий эффект переименовывания каталога или аналог «Распаковать здесь»:

tar -C /home/admin/mytar -xvf admin.tar.gz —strip-components 1

* каталог /home/admin/mytar заранее должен быть создан; —strip-components 1 пропустит одну вложенную папку внутри архива.

Исключение файлов по маске

Если необходимо пропустить некоторые файлы, вводим команду с ключом —exclude:

tar —exclude=’sess_*’ -czvf archive.tar.gz /wwwsite

* в данном примере мы создадим архив archive.tar.gz, в котором не будет файлов, начинающихся на sess_.

Также можно исключить несколько файлов или папок, добавляя несколько опций exclude:

tar —exclude=’/data/recycle’ —exclude=’*.tmp’ zcf /backup/samba/2021-08-29.tar.gz /data/

* в данном примере мы исключим папку recycle и файлы, которые заканчиваются на .tmp

Работа с архивами, разбитыми на части

Разбить архив на части может понадобиться по разным причинам — нехватка места на носителе, необходимость отправки файлов по почте и так далее.

Чтобы создать архив, разбитый на части, вводим команду:

tar -zcvf — /root | split -b 100M — root_home.tar.gz

* данная команда создаст архив каталога /root и разобьет его на части по 100 Мб.

В итоге мы получим, примерно, такую картину:

root_home.tar.gzaa root_home.tar.gzac root_home.tar.gzae
root_home.tar.gzag root_home.tar.gzai root_home.tar.gzab
root_home.tar.gzad root_home.tar.gzaf root_home.tar.gzah

Чтобы собрать архив и восстановить его, вводим команду:

cat root_home.tar.gz* | tar -zxv

Описание ключей tar

Команды для действия

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

* нельзя использовать несколько вышеперечисленных ключей в одной команде.

Дополнительные опции

Ключ Описание
—atime-preserve Оставить прежнюю метку времени доступа для файла.
-b N Задать размер блока N x 512.
-C Смена каталога. По умолчанию, используется тот, в котором мы находимся.
—checkpoint Показать имена папок при чтении архивного файла.
-G Использование старого формата инкрементального резервирования при отображении или извлечения.
-g Использование нового формата инкрементального резервирования при отображении или извлечения.
-h Не дублировать символьные ссылки. Только файлы, на которые указывают эти симлинки.
-i Игнорировать блоки нулей.
-j Использование bzip2.
—ignore-failed-read Игнорировать не читаемые файлы.
-k При распаковке, существующие файлы не заменяются соответствующими файлами из архива.
-L N Смена магнитной ленты после N*1024 байт.
-m При извлечении игнорировать время модификации объекта.
-M Многотомные архивы.
-N DATE Сохранять только более новые файлы относительно DATE
-O Направление извлекаемого на стандартный вывод.
-p Извлечение защищенной информации.
-P Не отбрасывает начальный слэш (/) из имен.
-s Сортировка файлов при извлечении.
—preserve Аналогично -ps
—remove-files Удалить исходные файлы после добавления в архив.
—same-owner Сохранить владельца при извлечении.
—totals Вывод байт при создании архива.
-v Протоколирование действий — отображение списка объектов, над которыми происходит действие.
-V NAME Создание архива на томе с меткой NAME.
—version Показать версию tar.
-w Требовать подтверждения для каждого действия.
-W Проверка архива после записи.
—exclude FILE Исключить файл FILE.
-X FILE Исключить файлы FILE.
-Z Фильтрует архив с помощью compress.
-z Использование gzip.

* актуальный список опций можно получить командой man tar.

Tar не работает с zip-архивами. В системах UNIX для этого используем утилиты zip и unzip. Для начала, ставим нужные пакеты:

yum install zip unzip

apt-get install zip unzip

pkg install zip unzip

* соответственно, для RPM based, deb based, BSD based.

zip -r archive.zip /home/dmosk

* создает архив каталога /home/dmosk в файл archive.zip.

Windows

В системе на базе Windows встроенными средствами можно распаковать только ZIP-архивы. Для работы с разными архивами рекомендуется поставить архиватор, например 7-Zip.

Источник

How To Open a Tar.gz File In Linux / Unix

I ‘ve received a file called date.tar.gz. How do I open/extract/unpack a tar.gz file on Linux or Unix like operating systems using shell prompt?

A .tar.gz (also .tgz ) file is nothing but an archive. It is a file that acts as a container for other files. An archive can contain many files, folders, and subfolders, usually in compressed form using gzip or bzip2 program on Unix like operating systems.

Tutorial details
Difficulty level Easy
Root privileges No
Requirements tar
Est. reading time 4 mintues

Say hi to tar command line tool

You need to use the tar command which can create and manipulate archive files in .tar.gz under Unix like operating systems. Open a command-line terminal (select Applications > Accessories > Terminal), and then type the following to open and extract a .tar.gz file:

Where options are as follows:

  • -z : Uncompress the resulting archive with gzip command.
  • -x : Extract to disk from the archive.
  • -v : Produce verbose output i.e. show progress and file names while extracting files.
  • -f data.tar.gz : Read the archive from the specified file called data.tar.gz.

How To Open a Tar.gz File In Linux / Unix System

By defaults files will be extracted into the current directory. To change the directory use -C option. In this example, extract files in /data/projects directory:

To view a detailed table of contents (list all files) for this archive, enter:

  • 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

file-roller : GUI tool

GNOME Archive Manager Running on my Ubuntu 20.04 LTS desktop

Fig.01: Gnome Archive Manager

Fig.02: Linux: Open Files With an Archive Manager

Fig.03: Linux GUI Extract Files From an Archive — data.tar.gz

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

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

can i access n edit the complicated structured tar files

Get the Midnight commander:

sudo apt-get install mc

Ah been meaning to install this for the next time I have the privilage to use an ssh to fix a computer system. Thanks for the reminder.

Thank you very much its super very effective

Yawn. This is why linux after all these years is a waste of space. In 10 years you still haven’t managed to create a double click installer. Common fanboys hit me with your arrogant linux attitude. I don’t want to hear your explanations no one wants tar files no one wants to use a terminal and until you have a double click install with zip, rar and 7z support i will always call linux rubbish. see yah.

You are dumber than Ted Kennedy the night he crashed his car and brutally shred apart and killed his date. Keep voting Democrat.

Actually it is supported and additional archieve formats can be added with ease to the linux system; many users prefer the terminal, why you may ask because it is power which cannot be met by any GUI tool which is the case on almost every operating system. Also download a .deb file and double-click it; seriously I don’t think you’ve ever had the privillage of using a unix system or linux system for that matter.

Get a life or get a job as I see there is absolutely no reason to discourage new users simply because you are ignorant or lack the skills required to have an even primitive knowledge of the same system that runs most of world’s webservers and 99% of the world’s fastest supercomputers.

So we’re all a bunch of fanboys; I personally have a custom kernel and my system runs even cooler under linux than Windows. I’ve logged hundreds of hours in Windows troubleshooting issues ranging from rootkits to the occassional user whom fails to understand that doubleclicking that exe file will start the installer (same thing as double-clicking a .deb file on a debian/debian-based system).

By the time I was 18 I was an IT whom had worked on databases worth millions. If you honestly expect me to believe for even a moment that you have even experience once so ever on these systems then you are dumber than I first thought. I’ve worked alongside software engineers and systems analysts and have served as an advisor for computer systems all of these were Windows.

Also there was a study done which showed that linux (study used Ubuntu) is more user-friendly than Windows. Now if you want to start an debate on macs I’ll have to remind you that macs are unix-based and after it took 6 months for Apple to patch only one security threat when the linux kernel can be patched in hours.

I’m done…I don’t waste my time with trolls…

…I have a database to write

That’s a silly comment.

It’s because of idiots like you with that mindset faded away into obscurity because they refused to learn new and emerging technologies….much like the ex-mainframer’s I used to work with at one of my prior places of employment (Chubb & Son’s, Inc. in New Jersey) who refused to want to learn Unix or any other operating system because they believed nothing could be superior to Big Iron, as mainframes are called…..after the datacenter was outsourced many of them could not find employment because of their outdated 70’s experience and technical skills and had to take jobs at Lowes, Home Depot, WalMart, KMart, and other non-technology companies….WHY. Because they failed to stay current!! You sound just like that group of losers who had nothing to do but bash this system and that system in favor of Big Iron without thinking ahead to where the future may take them…..

Mojang, remove the Steve skin! That is a stupid comment.

As a decade long linux user I have to say…you’re absolutely right. It’s really frustrating after all this time that a double click option isn’t available. Sorry chaps, it’s the truth.

The Rule of Three is in full effect. Example:

This guy’s a douche.

Go spend your dads money on an expensive laptop made of glue, and enjoy double clicking on Facebook at Starbucks, douche.

Oh yeah, by the way… this guy’s a douche.

You are a Clown. You are just lashing out cause you have no clue how to navigate in such a straight forward system.

any chance I could unzip a tar file on an android fone?

install busybox if the tar command isn’t already installed

Super…using TAR is easy and was able to unpack Eclipse compiler into Linux.
Thanks

Источник

Читайте также:  Драйвер bluetooth для windows 10 64 bit acer aspire
Оцените статью