📜  extract tar linux - Shell-Bash (1)

📅  最后修改于: 2023-12-03 15:14:57.837000             🧑  作者: Mango

Extracting TAR files in Linux - Shell/Bash

Introduction

In Linux, TAR (Tape Archive) is a common archive format used to combine multiple files into a single file for easy storage, transportation, and distribution. The TAR command-line utility is used to create and extract TAR files. This guide will explain how to extract TAR files using Shell/Bash scripting.

Code Example

Below is an example Bash script that demonstrates how to extract a TAR file:

#!/bin/bash

# Check if the TAR file exists
if [ ! -f "archive.tar" ]; then
  echo "TAR file not found!"
  exit 1
fi

# Extract the TAR file
tar -xvf archive.tar -C /extracted_folder

echo "TAR file extracted successfully!"
Explanation

Let's go through the code example step by step:

  1. The script starts with a shebang #!/bin/bash, which indicates that the script should be run by the Bash shell.
  2. The if statement checks if the TAR file archive.tar exists in the current directory. If it doesn't, the script displays an error message and exits with a non-zero status code.
  3. The tar command is used to extract the TAR file. The options used are:
    • -x: Extracts files from the archive.
    • -v: Verbose mode, displays detailed information about the extraction process.
    • -f: Specifies the TAR file to extract.
    • -C: Specifies the directory where the files will be extracted.
  4. After the extraction is complete, the script displays a success message.
Usage

To use the above script, follow these steps:

  1. Save the script to a file, e.g., extract_tar.sh.
  2. Make the script executable using the command chmod +x extract_tar.sh.
  3. Place the TAR file archive.tar in the same directory as the script.
  4. Run the script using the command ./extract_tar.sh.
  5. The extracted files will be stored in the /extracted_folder directory.

Make sure to replace archive.tar with the name of your TAR file and /extracted_folder with the desired extraction directory.

Conclusion

Extracting TAR files using Shell/Bash scripting is a straightforward process. By using the tar command with the appropriate options, you can easily extract the contents of TAR archives.