Created
April 28, 2021 12:05
-
-
Save CHERTS/a94d89c1625acd01b6ecaf3a4e6b20a2 to your computer and use it in GitHub Desktop.
Wget on pure Bash
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
#!/usr/bin/env bash | |
# | |
# Program: Wget on pure bash <wget_on_bash.sh> | |
# | |
# Author: Mikhail Grigorev <sleuthhound at gmail dot com> | |
# | |
# Current Version: 1.0.0 | |
# | |
# License: | |
# This program is distributed in the hope that it will be useful, | |
# but WITHOUT ANY WARRANTY; without even the implied warranty of | |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | |
# | |
_usage() { | |
echo "" | |
echo "Usage: $0 \"http://http.programs74.ru/\" \"/tmp/result\"" | |
echo "" | |
exit 1 | |
} | |
[ $# -ne 2 ] && _usage | |
# wget on bash | |
function _wget() { | |
local URL=$1 | |
local LOCALFILE=${2:-"/tmp/test"} | |
local TMPFILE=$2.tmp | |
read proto server path <<<$(echo ${URL//// }) | |
local SCHEME=${proto//:*} | |
local PATH=/${path// //} | |
local HOST=${server//:*} | |
local PORT=${server//*:} | |
if [[ "${SCHEME}" != "http" ]]; then | |
echo "ERROR: Sorry, support only http protocol." | |
return 1 | |
fi | |
if [[ "${HOST}" = "${PORT}" ]]; then | |
PORT=80 | |
fi | |
# Open tcp connection and check hostname/port | |
(exec 3<>/dev/tcp/${HOST}/${PORT}) >/dev/null 2>&1 | |
if [ $? -ne 0 ]; then | |
echo "ERROR: Name or service not known." | |
return $? | |
fi | |
# Close tcp | |
exec 3>&- | |
# Open tcp connection | |
exec 3<>/dev/tcp/${HOST}/${PORT} | |
echo -en "GET ${PATH} HTTP/1.1\r\nHost: ${HOST}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n" >&3 | |
if [ $? -ne 0 ]; then | |
return $? | |
fi | |
/bin/cat <&3 > "${TMPFILE}" | |
/bin/tail "${TMPFILE}" -n +$((`/bin/sed "${TMPFILE}" -e '/^\r$/q' | /bin/wc -l`+1)) > "${LOCALFILE}" | |
/bin/rm -f "${TMPFILE}" >/dev/null 2>&1 | |
# Close tcp | |
exec 3>&- | |
} | |
if [ -f "$2" ]; then | |
echo "ERROR: File '$2' already exist." | |
exit 1 | |
fi | |
echo "Downloading '$1' and save to '$2'" | |
_wget "$1" "$2" | |
if [ -f "$2" ]; then | |
echo "Download done, check file ;)" | |
else | |
echo "ERROR: Something went wrong." | |
exit 1 | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment