简体   繁体   中英

How to capture the file size from a URL and use it in Shell scripting

URL_C="any url"
length_C=$(curl -sI $URL_C | grep Content-Length | cut -d ' ' -f 2)
answer_C=$(awk -v len=$length_C 'BEGIN{printf "%.0f\n", len/1024}')

Will the variable $answer_C capture the file size ?

Is Content-Length the correct way ?

You can retrieve headers, then try to awk the Content-Length value as @user000001 suggested, and if not found, download file to count chars :

url="your_url"
size=$(curl -sI "$url" | awk '/Content-Length/{gsub("\\r", ""); print $2}')
if [ -z "$size" ]; then 
    size=$(curl -s "$url" | wc -c)
fi
printf "%s : %d bytes\n" "$url" "$size"

Note : gsub("\\\\r", "") in the awk command is for removing carriage returns from the curl output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM