Skip to content

Instantly share code, notes, and snippets.

@odinokov
Last active April 4, 2023 04:33
Show Gist options
  • Save odinokov/a82146a04120bb3635a559579753d047 to your computer and use it in GitHub Desktop.
Save odinokov/a82146a04120bb3635a559579753d047 to your computer and use it in GitHub Desktop.
a demo script
# This function downloads a file from a given URL using wget command.
# If the file already exists, it will be checked to see if it has been downloaded completely.
# If the file was previously partially downloaded, the function will continue the download from where it was left off.
# If the file does not exist, the function will download it from scratch.
# If the download fails, an error message is displayed and the script exits with a non-zero exit status.
#
# Args:
# URL: the URL to download the file from.
# OUT: optional output directory for the downloaded file. If not provided, the file will be downloaded to the current directory.
#
# Returns:
# 0 if the download is successful, 1 if it fails.
download_file() {
local URL="$1"
local OUT="${2:-.}" # Default to current directory if OUT is not specified
# Check if wget is available
if ! command -v wget &> /dev/null; then
printf "Error: wget command not found\n"
return 1
fi
# Extract the filename from the URL
local FILENAME=$(basename "$URL")
# Remove trailing slash from OUT if it exists and append the output directory if specified
if [ "$OUT" != "." ]; then
FILENAME="${OUT%/}/$FILENAME"
fi
# Check if the file already exists and has been downloaded completely
if [ -e "$FILENAME" ] && ! [ -e "$FILENAME.tmp" ]; then
printf "File %s already exists.\n" "$FILENAME"
return 0
fi
# Check if the partially downloaded file exists
if [ -e "$FILENAME.tmp" ]; then
# Continue downloading from where we left off
wget --continue --show-progress -qO "$FILENAME.tmp" "$URL"
else
# Download the file from scratch
wget --show-progress -qO "$FILENAME.tmp" "$URL"
fi
# Check if the download was successful
if [ $? -eq 0 ]; then
# Rename the tmp file to the original filename
mv -q "$FILENAME.tmp" "$FILENAME"
printf "Download successful: %s\n" "$FILENAME"
return 0
else
printf "Download failed: %s\n" "$FILENAME"
rm -f "$FILENAME.tmp" # Remove partial download
return 1
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment