Created
July 19, 2018 06:27
-
-
Save alice1017/47ff453c0545a42313403b85c1cc6f52 to your computer and use it in GitHub Desktop.
The get.sh is a command line tool for download a file from URL and extract an archived file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# coding: utf-8 | |
# Check arguments | |
if [ "$#" = "0" ];then | |
{ | |
echo "usage: get [URL]" | |
echo "" | |
echo "This get script can download a file from URL argument, and extract it." | |
} 1>&2 | |
exit 1 | |
fi | |
# Variables | |
typeset -r TARGET="$1" | |
typeset -r DEST="$HOME/local/src" | |
typeset filename | |
typeset exit_code | |
# Functions | |
function is_url() { | |
# is_url - check the $1 is url or not | |
# args $1: URL string | |
local target=$1 | |
if [[ "$target" =~ ^(http|https):// ]];then | |
return 0 | |
else | |
return 1 | |
fi | |
} | |
function download() { | |
# download - download the $1 | |
# args $1: URL string | |
local url="$1" | |
local filename | |
if is_url "$url";then | |
filename="$(basename "$url")" | |
(curl -# -L -o "$filename" "$url" & wait $!) | |
echo "$filename" | |
return $? | |
else | |
printf "'%s' is not a url\n" "$url" 1>&2 | |
exit 1 | |
fi | |
} | |
function extract() { | |
# extract - extract a file | |
# args $1: archived file name | |
local filename="$1" | |
if [[ "$filename" =~ \.tar\.gz$ ]];then | |
(tar xvf $filename & wait $!) | |
return $? | |
elif [[ "$filename" =~ \.zip$ ]];then | |
(gzip $filename & wait $!) | |
return $? | |
else | |
return 2 | |
fi | |
} | |
# Main | |
cd "$DEST" | |
# 1. download | |
filename="$(download "$TARGET")" | |
exit_code=$? | |
if [ ! "$exit_code" = "0" ];then | |
echo "The download was failed" 1>&2 | |
exit 1 | |
fi | |
# 2. extract | |
extract "$filename" | |
exit_code=$? | |
if [ "$exit_code" = "0" ];then | |
echo "The download & extract was successed." | |
printf "An extracted file saved here: '%s'\n" "$DEST/$filename" | |
exit 0 | |
elif [ "$exit_code" = "2" ];then | |
echo "The download was successed." | |
printf "A downloaded file saved here: '%s'\n" "$DEST/$filename" | |
exit 0 | |
else | |
echo "The extract was failed." 1>&2 | |
exit 1 | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment