#!/bin/bash ###################################################################################################### # # Script for curl to support resumable multi-part download. #
url=$1 exename=`basename $0`
# How many "parts" will the target file be divided into? declare -i parts=5
read -ep "Please input the target directory: " targetdir read -ep "Please input the outfile name: " outfile
[ -z "$targetdir" ] && targetdir="./" cd $targetdir||exit 2
[ -z "$outfile" ] && outfile=`basename $1`
length=`curl -s -I $url|grep Content-Length|sed s/[^0-9]//g` #length=`curl -s -I $url|grep Content-Length|awk '{print $2}'|sed s/[^0-9]//` if [ -z "$length" ]; then echo "cann't get the length of the target file" exit 1 fi let "length = $length"
#To get how many bytes have been downloaded if [ -e $outfile$i ]; then offset=`ls -l $outfile$i|awk '{print $5}'` else offset=0 fi let "offset = $offset"
if [ $i -lt $parts ]; then if [ $offset -lt $lsession ]; then curl -r $(($curr+$offset))-$(($curr+$lsession-1)) $url >> $outfile$i & fi else if [ $offset -lt $(($length-$(($lsession*$(($parts-1)))))) ]; then curl -r $(($curr+$offset))- $url >> $outfile$i & fi fi
curr=$(($curr+$lsession))
done
#To judge if all curl threads have terminated. while true; do hasCurl=`ps -A -o ppid,cmd|grep $$|grep -v "$exename"|grep -v "grep"|grep curl` [ -z "$hasCurl" ] && break sleep 10 done
finished="true" for (( i=1; i<=$parts; i=i+1 )) do if [ -e $outfile$i ]; then offset=`ls -l $outfile$i|awk '{print $5}'` else offset=0 fi let "offset = $offset" if [ $i -lt $parts ]; then if [ $offset -lt $lsession ]; then finished="false" break fi else if [ $offset -lt $(($length-$(($lsession*$(($parts-1)))))) ]; then finished="false" break fi fi done
if [ "$finished" == "true" ]; then break fi done
echo "All parts have been downloaded. Merging..."
mv --backup=t $outfile"1" $outfile for (( i=2; i<=$parts; i=i+1)) do cat $outfile$i >> $outfile rm $outfile$i done