Geekflare recibe el apoyo de nuestra audiencia. Podemos ganar comisiones de afiliación de los enlaces de compra en este sitio.
En Linux y Redes de ordenadores Última actualización: 25 de septiembre de 2023
Compartir en:
Escáner de seguridad de aplicaciones web Invicti - la única solución que ofrece verificación automática de vulnerabilidades con Proof-Based Scanning™.

tar es uno de los formatos de archivo de ficheros más populares disponibles en los sistemas basados en Unix y Linux

El propio nombre deriva de Cinta ARchivo, ya que se desarrolló para escribir datos secuenciales en dispositivos de cinta. A veces también se le denomina tarball

Por defecto, tar sólo archiva los ficheros sin compresión pero utilizando algunas porciones. Podemos utilizar diferentes técnicas de compresión para obtener una salida comprimida. La utilidad tar suele estar incluida por defecto en la mayoría de las distribuciones de Linux, y el propio formato es compatible con otros sistemas operativos, incluidos Windows y macOS, a través de diferentes herramientas y utilidades

Cubriremos algunos de los ejemplos y usos más comunes del comando tar y sus banderas soportadas en este artículo

Así que empecemos..

Crear archivo tar

Para crear un archivo simple sin comprimir, la sintaxis del comando tar es

$ tar cvf <nombre-archivo-tar> <archivos-a-archivar&gt

Aquí las banderas c significa creación, v para salida verbosa y f para especificar el nombre del archivo tar. Por convención, especifique el nombre del archivo tar con extensión .tar. Los archivos a archivar pueden especificarse con comodines o como nombres de archivo/rutas individuales o múltiples

Como ejemplo, tengo tres archivos en mi directorio

$ ls -l
total 12

-rw-r-r-

 1 abhisheknair abhisheknair 13 Sep 12 20:08 file1.txt

-rw-r-r-

 1 abhisheknair abhisheknair 19 Sep 12 20:08 file2.txt
-rw-r--r-- 1 abhisheknair abhisheknair 24 Sep 12 20:08 file3.txt

$

 ls -l total 12 -rw-r--r-- 1 abhisheknair abhisheknair 13 Sep 12 20:08 file1.txt

Y quiero crear un archivo tar que contenga los tres ficheros, se puede hacer como

$ tar cvf archivo.tar *
archivo1.txt
archivo2.txt
archivo3.txt

$

 ls -l archivo.tar

-rw-r-r-

 1 abhisheknair abhisheknair 10240 12 sep 20:15 archivo.tar

$
También puedo especificar sólo archivos concretos para archivar, como

$ tar cvf archivo1.tar archivo1.txt archivo2.txt
archivo1.txt
archivo2.txt

$

 ls -l archivo1.tar

-rw-r-r-

 1 abhisheknair abhisheknair 10240 sep 12 20:15 archivo1.tar

$

Crear archivo comprimido (GZ)

tar no sólo permite archivar ficheros, sino también comprimirlos para ahorrar espacio. Uno de los formatos de compresión más populares es gunzip, normalmente representado por la extensión .gz after .tar o como tgz. Podemos utilizar la bandera z para especificar que necesitamos que los archivos se compriman utilizando gunzip. He aquí un ejemplo

$ tar cvzf archivo.tar.gz archivo*
archivo1.txt
archivo2.txt
archivo3.txt

$

 ls -l archivo.tar archivo.tar.gz

-rw-r-r-

 1 abhisheknair abhisheknair 10240 Sep 12 20:15 archivo.tar

-rw-r-r-

 1 abhisheknair abhisheknair 188 Sep 12 20:21 archivo.tar.gz

$

 tar cvzf archivo.tar.gz archivo.tar.gz

Puede observar que el tamaño de ambos ficheros de archivo es sustancialmente diferente a pesar de que ambos contienen los mismos tres ficheros. Esto se debe al uso de la compresión mediante la bandera z

Crear archivo comprimido (BZ2)

tar admite otros formatos de compresión. Uno de ellos es bz2 o bzip2 que se representa por la extensión tar.bz2 o a veces como tbz2. Puede proporcionarle un tamaño de archivo menor, pero a su vez consume más CPU, por lo que el proceso de compresión/descompresión podría ser más lento que el del archivo gz

Ejemplo

$ tar cvjf archivo.tar.bz2 archivo*
archivo1.txt
archivo2.txt
archivo3.txt
$ ls -l archivo.tar archivo.tar.gz archivo.tar.bz2
-rw-r--r-- 1 abhisheknair abhisheknair 10240 12 sep 20:15 archivo.tar
-rw-r--r-- 1 abhisheknair abhisheknair 212 Sep 12 20:25 archive.tar.bz2
-rw-r--r-- 1 abhisheknair abhisheknair 188 Sep 12 20:21 archive.tar.gz
$ archivo archive.tar*
archive.tar:     Archivo POSIX tar (GNU)
archive.tar.bz2: datos comprimidos bzip2, tamaño de bloque = 900k
archive.tar.gz: datos comprimidos gzip, de Unix, tamaño original modulo 2^32 10240

$

Descomprimir todos los archivos

Un archivo tar (comprimido o sin comprimir) puede extraerse simplemente utilizando la opción x. Los ejemplos siguientes aclararán su uso

$ tar xvf archivo.tar
archivo1.txt
archivo2.txt
archivo3.txt
$ ls -l
total 24
-rw-r--r-- 1 abhisheknair abhisheknair 10240 Sep 19 18:25 archivo.tar
-rw-r--r-- 1 abhisheknair abhisheknair 13 Sep 12 20:08 archivo1.txt

-rw-r-r- 1 abhisheknair abhisheknair 19 Sep 12 20:08 file2

.txt

-rw-r-r-

 1 abhisheknair abhisheknair 24 Sep 12 20:08 file3.txt

$
Esto funciona para un archivo comprimido gz como

$ tar xvf archivo.tar.gz
archivo1.txt
archivo2.txt
archivo3.txt
$ ls -l
total 16
-rw-r--r-- 1 abhisheknair abhisheknair 188 Sep 19 18:27 archivo.tar.gz

-rw-r-r- 1 abhisheknair abhisheknair 13

 Sep 12 20:08 file1.txt

-rw-r-r-

 1 abhisheknair abhisheknair 19 Sep 12 20:08 file2.txt

-rw-r-r-

 1 abhisheknair abhisheknair 24 Sep 12 20:08 file3.txt

$
O incluso para un archivo comprimido bz2 como

$ tar xvf archivo.tar.bz2
archivo1.txt
archivo2.txt
archivo3.txt
$ ls -l
total 16
-rw-r--r-- 1 abhisheknair abhisheknair 212 Sep 19 18:31 archivo.tar.bz2

-rw-r-r- 1 abhisheknair abhisheknair 13 Sep

 12 20:08 file1.txt

-rw-r-r-

 1 abhisheknair abhisheknair 19 Sep 12 20:08 file2.txt

-rw-r-r-

 1 abhisheknair abhisheknair 24 Sep 12 20:08 file3.txt

$

Listar el contenido del tar

Para listar el contenido de un archivo tar, puede utilizar la bandera t como se muestra a continuación

$ tar tvf archivo.tar.bz2

-rw-r-r-

 abhisheknair/abhisheknair 13 2021-09-12 20:08 archivo1.txt

-rw-r-r-

 abhisheknair/abhisheknair 19 2021-09-12 20:08 archivo2.txt

-rw-r-r-

 abhisheknair/abhisheknair 24 2021-09-12 20:08 archivo3.txt

$

Untar archivos específicos

Se puede extraer un solo archivo de un archivo tar o tar.gz o tar.bz2 especificando el nombre del archivo como

$ tar xvf archivo.tar.bz2 archivo1.txt
archivo1.txt

$

 ls -l
total 8

-rw-r-r-

 1 abhisheknair abhisheknair 212 Sep 19 18:31 archivo.tar.bz2

-rw-r-r-

 1 abhisheknair abhisheknair 13 Sep 12 20:08 archivo1.txt

$
Del mismo modo, puede especificar varios nombres de archivo separados por espacios para extraerlos juntos de una sola vez

$ tar xvf archivo.tar.bz2 archivo1.txt archivo3.txt
archivo1.txt
archivo3.txt
$ ls -l
total 12
-rw-r--r-- 1 abhisheknair abhisheknair 212 Sep 19 18:31 archivo.tar.bz2

-rw-r-r- 1 abhisheknair

 abhisheknair 13 Sep 12 20:08 file1.txt

-rw-r-r-

 1 abhisheknair abhisheknair 24 Sep 12 20:08 file3.txt

$

Untar usando Wildcard

Para extraer uno o más archivos utilizando un PATRÓN comodín, utilice la bandera --wildcards

$ tar xvf archivo.tar.bz2 --wildcards "archivo*"
archivo1.txt
archivo2.txt
archivo3.txt
$ ls -l
total 16
-rw-r--r-- 1 abhisheknair abhisheknair 212 Sep 19 18:31 archivo.tar.bz2

-rw-r-r- 1 abhisheknair abhisheknair 13 Sep

 12 20:08 file1.txt

-rw-r-r-

 1 abhisheknair abhisheknair 19 Sep 12 20:08 file2.txt

-rw-r-r-

 1 abhisheknair abhisheknair 24 Sep 12 20:08 file3.txt

$

Añadir ficheros al archivo

Se pueden añadir/adjuntar nuevos archivos a los archivos tar sin comprimir existentes utilizando la bandera r o --append con los nuevos nombres de archivo o un patrón de comodines (recuerde que esto sólo funciona con archivos .tar sin comprimir y no con los formatos comprimidos tar.gz o tar.bz2 )

$ tar rvf archive.tar archivo-nuevo*
archivo-nuevo.txt
archivo-nuevo2.txt
$ tar tvf archive.tar
-rw-r--r-- abhisheknair/abhisheknair 13 2021-09-12 20:08 archivo1.txt
-rw-r--r-- abhisheknair/abhisheknair 19 2021-09-12 20:08 file2.txt
-rw-r--r-- abhisheknair/abhisheknair 24 2021-09-12 20:08 file3.txt
-rw-r--r-- abhisheknair/abhisheknair 15 2021-09-19 18:59 file2.txt
-rw-r--r-- abhisheknair/abhisheknair 10 2021-09-19 18:58 file4.

txt


-rw-r--r-- abhisheknair/abhisheknair 9 2021-09-19 19:10
 archivo-nuevo.txt

-rw-r-r-

 abhisheknair/abhisheknair 9 2021-09-19 19:10 archivo-nuevo2.txt

$
Puede observar que al listar el contenido de archive. tar aparecen de nuevo los dos archivos recién añadidos

Borrar archivos del archivo

Es posible eliminar archivos específicos de un archivo tar utilizando la bandera --delete como se muestra a continuación (compare el listado tar anterior y posterior a la eliminación de archivos)

$ tar tvf archive.tar
-rw-r--r-- abhisheknair/abhisheknair 13 2021-09-12 20:08 file1.txt
-rw-r--r-- abhisheknair/abhisheknair 19 2021-09-12 20:08 file2.txt
-rw-r--r-- abhisheknair/abhisheknair 24 2021-09-12 20:08 file3.txt
-rw-r--r-- abhisheknair/abhisheknair 15 2021-09-19 18:59 file2.txt
-rw-r--r-- abhisheknair/abhisheknair 10 2021-09-19 18:58 file4.txt
-rw-r--r-- abhisheknair/abhisheknair 9 2021-09-19 19:10 file-new.txt
-rw-r--r-- abhisheknair/abhisheknair 9 2021-09-19 19:10 archivo-nuevo2.txt
$ tar --delete -f archivo.tar archivo-nuevo.txt archivo-nuevo2.txt
$ tar tvf archivo.tar
-rw-r--r-- abhisheknair/abhisheknair 13 2021-09-12 20:08 archivo1.txt
-rw-r--r-- abhisheknair/abhisheknair 19 2021-09-12 20:08 file2.txt
-rw-r--r-- abhisheknair/abhisheknair 24 2021-09-12 20:08 file3.txt

-rw-r-r- abhisheknair/abhisheknair 15

 2021-09-19 18:59 file2.txt

-rw-r-r-

 abhisheknair/abhisheknair 10 2021-09-19 18:58 file4.txt

$
De nuevo, esto sólo funciona para tarballs sin comprimir y fallará para formatos de archivo comprimidos

Crear con Verify

Al crear archivos tar sin comprimir, puede verificar el contenido del archivo utilizando la bandera W como

$ tar cvfW archivo.tar archivo*.txt
archivo1.txt
archivo2.txt
archivo3.txt
Verificar archivo1.txt
Verificar archivo2.txt
Verificar archivo3.txt

$
Esto no se puede utilizar con banderas de compresión aunque puede comprimir el archivo tar creado más tarde utilizando gzip u otras herramientas

Extraer alquitrán a una carpeta

Si desea extraer el contenido de su archivo tar a una carpeta específica en lugar del directorio actual, utilice la bandera -C con la ruta del directorio como se muestra a continuación

$ tar xvf archivo.tar -C nuevo-directorio/
archivo1.txt
archivo2.txt
archivo3.txt
archivo2.txt
archivo4.txt
$ ls -l nuevo-directorio/
total 16
-rw-r--r-- 1 abhisheknair abhisheknair 13 Sep 12 20:08 archivo1.txt

-rw-r-r- 1 abhisheknair abhisheknair 15

 Sep 19 18:59 file2.txt

-rw-r-r-

 1 abhisheknair abhisheknair 24 Sep 12 20:08 file3.txt

-rw-r-r-

 1 abhisheknair abhisheknair 10 Sep 19 18:58 file4.txt

$

Usar bandera dif

Puede utilizar la bandera --diff o d para encontrar cualquier cambio entre los ficheros del archivo tar y los del sistema de ficheros. Aquí hay un ejemplo que ejecuta el diff una vez cuando el archivo dentro del tar y fuera era el mismo. Después de actualizar el archivo, se ejecutó una vez más para mostrar la diferencia en la salida

$ tar dvf archive.tar archivo4.txt
archivo4.txt
$
$ echo newline > archivo4.txt
$
$ tar dvf archive.tar archivo4.txt
archivo4.txt
archivo4.txt: Mod time differs
archivo4.txt:

El tamaño difiere


$

Excluir archivos

Excluir archivos específicos puede ser un requisito a la hora de crear archivos tar. Esto puede lograrse con la bandera --exclude

$ tar --exclude="dir/fichero2.txt" --exclude="dir/fichero-nuevo*.txt" -cvzf archive.tar.gz dir/
dir/
dir/fichero1.txt
dir/fichero3.txt
$ ls -l dir
total 24
-rw-r--r-- 1 abhisheknair abhisheknair 9 Sep 19 19:10 file-new.txt
-rw-r--r-- 1 abhisheknair abhisheknair 9 Sep 19 19:10 archivo-nuevo2.txt
-rw-r--r-- 1 abhisheknair abhisheknair 5 Sep 19 19:20 archivo-nuevo3.txt
-rw-r--r-- 1 abhisheknair abhisheknair 5 Sep 19 19:27 archivo1.txt
-rw-r--r-- 1 abhisheknair abhisheknair 6 Sep 19 19:27 archivo2.txt
-rw-r--r-- 1 abhisheknair abhisheknair 8 Sep 19 19:27 archivo3.txt
$ tar tvf archive.tar.gz
drwxr-xr-x abhisheknair/abhisheknair 0 2021-09-19 19:30 dir/

-rw-r-r-

 abhisheknair/abhisheknair 5 2021-09-19 19:27 dir/fichero1.txt

-rw-r-r-

 abhisheknair/abhisheknair 8 2021-09-19 19:27 dir/fichero3.txt

$
Como puede observar en la salida anterior, podemos especificar el indicador --exclude varias veces para especificar varios nombres de archivo o patrones en la condición AND. Observe que de los seis archivos del dir del ejemplo anterior, sólo dos archivos cumplían la condición para ser incluidos en archive.at.gz

Ver el tamaño del contenido tar

Podemos obtener el tamaño del contenido de un archivo tar comprimido utilizando el siguiente comando

$ tar tvf archivo.tar.gz
-rw-r--r-- abhisheknair/abhisheknair 13 2021-09-12 20:08 archivo1.txt
-rw-r--r-- abhisheknair/abhisheknair 19 2021-09-12 20:08 archivo2.txt

-rw-r-r-

 abhisheknair/abhisheknair 24 2021-09-12 20:08 file3.txt
$ tar -xzf archive.tar.gz --to-stdout|wc -c
56

$
De forma similar para archivo bz2

$ tar tvf archivo.tar.bz2
-rw-r--r-- abhisheknair/abhisheknair 13 2021-09-12 20:08 archivo1.txt
-rw-r--r-- abhisheknair/abhisheknair 19 2021-09-12 20:08 archivo2.txt

-rw-r-r-

 abhisheknair/abhisheknair 24 2021-09-12 20:08 file3.txt
$ tar -xjf archive.tar.bz2 --to-stdout|wc -c
56

$

Conservar los permisos

Por defecto, el comando tar preserva los permisos de los ficheros y directorios que está archivando aunque puede especificarlo explícitamente utilizando la bandera -p o --preserve-permissions como se muestra a continuación

$ tar cvpzf archivo.tar.gz *.txt
archivo1.txt
archivo2.txt
archivo3.txt

$

Resumen 👨‍💻

tar es una utilidad útil en los sistemas Unix/Linux desde hace mucho tiempo y se utilizaba principalmente en tareas de archivado y copias de seguridad. La utilidad ha evolucionado con muchas opciones a lo largo del tiempo. Puede utilizarse para tareas sencillas o complejas, siempre que se conozcan las características que ofrece. Este artículo cubre algunas de las operaciones básicas que puede realizar con el comando tar y muestra cómo puede ayudarle en su tareas diarias de administración del sistema

Consulte su página de manual man tar o utilice el comando tar --help o tar --usage para obtener más detalles.

  • Abhishek Nair
    Autor
Gracias a nuestros patrocinadores
Más lecturas sobre Linux
Potencia tu negocio
Algunas de las herramientas y servicios que le ayudarán a hacer crecer su negocio.
  • Invicti utiliza el Proof-Based Scanning™ para verificar automáticamente las vulnerabilidades identificadas y generar resultados procesables en tan solo unas horas.
    Pruebe Invicti
  • Web scraping, proxy residencial, gestor de proxy, desbloqueador web, rastreador de motores de búsqueda, y todo lo que necesita para recopilar datos web.
    Pruebe Brightdata
  • Monday.com es un sistema operativo de trabajo todo en uno que te ayuda a gestionar proyectos, tareas, trabajo, ventas, CRM, operaciones, flujos de trabajo y mucho más.
    Prueba Monday
  • Intruder es un escáner de vulnerabilidades en línea que encuentra puntos débiles de ciberseguridad en su infraestructura, para evitar costosas violaciones de datos.
    Prueba Intruder