---
title: Tar File(s) or Directories Using the Command Line
description: There are many reasons why we might need to Tar files and directories, here are a few helpful commands to get started.
date: 2020-04-03
tags: Tar, Compression, Command Line
source: https://brianchildress.co/blog/tar-files-and-directories-using-command-line
---

# Tar File(s) or Directories Using the Command Line

There are many reasons why we might need to Tar files and directories, we might need to upload or download file to and from a server or application, archive files for later retrieval, whatever the reason here are a few helpful commands to get started.

"Taring" is simply a concept where we create a _tarball_ of files and/or directories that are compressed and easier to manipulate and move within a system. Linux (most distros) and Mac have tar commands built into the operating system. 

In the terminal a simple `tar` command might look like:

```sh
tar -czvf myphotos.tar.gz /path/to/photos
```

The above command will compress all files/ directories at the supplied path _/path/to/photos_ into a single file with the given filename, _myphotos.tar.gz_. 

Following the `tar` command we can pass a series of flags that tell the tar process how to compress the files and what information should be returned. Here is a breakdown of some of the more popular flags:


| Flag :| : Description |
| :---: | :--- |
| `-c` | **C**reate a tar file (.tar.gz) |
| `-z` | Compression format, this will use .gzip (more common) |
| `-j` | Compression format, this will use .bz2 |
| `-v` | **V**erbose output, helpful for understanding and troubleshooting |
| `-f` | **F**ile to archive to |
| `-x` | E**x**tract files from a tarball |


### Examples:

_Tar a single file_

```sh
tar -czvf myphoto.tar.gz /path/to/special-photos/myphoto.png
```

_Tar a directory of files_

```sh
tar -czvf myphotos.tar.gz /path/to/photos
```

_Tar multiple files/directories_

```sh
tar -czvf myphotos.tar.gz /path/to/photos /another/path/to/photos /more/photos /path/to/special-photos/myphoto.png
```

_Excluding files/directories_


```sh
tar -czvf myphotos.tar.gz /path/to/photos --exclude="vacation"
```

_View files in a tar file_

This will list the files/directories contained within the tar file.

```sh
tar -ztvf myphotos.tar.gz
```

_Extract files_

```sh
tar -xzvf myphotos.tar.gz
```

Use the `-C` flag to extract files to a specific directory.

```sh
tar -xzvf myphotos.tar.gz -C ~/Desktop/
```


I found this [article](https://www.cyberciti.biz/faq/how-to-tar-a-file-in-linux-using-command-line/) particularly useful.
