How to compress and extract files and directories using tar in Bash?

To compress files and directories using tar in Bash, you can use the following command:

tar -czvf archive.tar.gz file1 file2 directory1

Explanation:

  • tar: The command to create or manipulate tar archives.
  • -czvf: Options for the tar command:
    • c: Create a new archive.
    • z: Compress the archive using gzip.
    • v: Verbose mode, displaying the processed files.
    • f: Specify the name of the archive file to create.
  • archive.tar.gz: The name of the archive file to be created.
  • file1 file2 directory1: The files and directories you want to include in the archive.

To extract files and directories from a tar archive, you can use the following command:

tar -xzvf archive.tar.gz

Explanation:

  • x: Extract files from the archive.
  • archive.tar.gz: The name of the archive file to be extracted.
  • z: Decompress the archive using gzip.
  • v: Verbose mode, displaying the extracted files.

Note: The -v option is optional and can be omitted if you don't want to see verbose output during the compression or extraction process.