BASH

Download and Extract a Remote gzipped Tar Archive

Use Bash to download a gzipped tar archive from a given URL and extract its contents into a specified local target directory.

#!/bin/bash

ARCHIVE_URL=$1
TARGET_DIR=$2
TEMP_ARCHIVE_NAME="downloaded_archive.tar.gz"

if [ -z "$ARCHIVE_URL" ] || [ -z "$TARGET_DIR" ]; then
    echo "Usage: $0 <archive_url> <target_directory>
"
    exit 1
fi

mkdir -p "$TARGET_DIR"

echo "Downloading $ARCHIVE_URL to $TEMP_ARCHIVE_NAME...
"
curl -sSL "$ARCHIVE_URL" -o "$TEMP_ARCHIVE_NAME"

if [ $? -ne 0 ]; then
    echo "Error: Failed to download archive.
"
    rm -f "$TEMP_ARCHIVE_NAME" # Clean up partial download
    exit 1
fi

echo "Extracting $TEMP_ARCHIVE_NAME to $TARGET_DIR...
"
tar -xzf "$TEMP_ARCHIVE_NAME" -C "$TARGET_DIR"

if [ $? -ne 0 ]; then
    echo "Error: Failed to extract archive.
"
    rm -f "$TEMP_ARCHIVE_NAME"
    exit 1
fi

echo "Cleanup: Removing $TEMP_ARCHIVE_NAME...
"
rm "$TEMP_ARCHIVE_NAME"

echo "Archive successfully downloaded and extracted to $TARGET_DIR.
"
How it works: This script provides a way to download and extract gzipped tar archives from a remote URL. It takes the archive's URL and a target directory for extraction as arguments. It first ensures the target directory exists, then uses `curl` to download the archive to a temporary file. After a successful download, `tar -xzf` extracts the contents into the specified `TARGET_DIR`. Finally, the temporary downloaded archive file is removed. This is useful for quickly fetching and unpacking software distributions, themes, or plugins.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs