-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuget.sh
76 lines (63 loc) · 1.72 KB
/
uget.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#!/bin/bash
## version
VERSION="0.0.1"
## output error to stderr
error () {
printf >&2 "error: %s\n" "${@}"
}
## output usage
usage () {
echo "usage: uget [url]"
}
## echoes the first number of response code
uget_helper_curl_first_number_response_code () {
declare -a responses_codes
IFS=$'\n'
full_output=($(curl -IL --silent $1))
for i in "${full_output[@]}"; do
responses_codes+=($(echo $i | grep HTTP))
done
last_http=$(expr ${#responses_codes[@]} - 1)
last_response_code=$(echo ${responses_codes[$last_http]} | cut -f2 -d' ')
echo ${last_response_code:0:1}
}
## check the response code from url and download if success. Otherwise, return 1
uget_helper_curl_check_then_download () {
first_number_response_code=$(uget_helper_curl_first_number_response_code $1)
if [ $first_number_response_code = 2 ] || [ $first_number_response_code = 3 ]; then
echo $1
curl -O $1
return 0
else
echo The provided resource \("$1"\) does not exists.
return 1
fi
}
# main entrance
uget () {
if [[ -z $1 ]]; then
echo An argument must be provided to be the target address to download.
return 1
fi
which curl > /dev/null
curl_exists=$?
which wget > /dev/null
wget_exists=$?
if [[ $wget_exists = 0 ]]; then
wget $1
elif [[ $curl_exists = 0 ]]; then
uget_helper_curl_check_then_download $1
else
echo Neither wget or curl utilities are installed in the system. The download can\'t proceed.
return 1
fi
}
## detect if being sourced and
## export if so else execute
## main function with args
if [[ ${BASH_SOURCE[0]} != $0 ]]; then
export -f uget
else
uget "${@}"
exit $?
fi