如何使用curl命令检索可下载文件的大小?

如何使用curl命令检索可下载文件的大小?

我在 shell 脚本中有一个要求,比如必须使用curl 命令从“url”下载文件。在下载该文件之前,我想在方法中处理相同的文件大小。

谁能帮我这个?

答案1

使用该-I选项仅检索标头,并查找“Content-Length”标头。-L如果需要遵循重定向,请添加该选项。例如:

$ curl -L -I https://cdimage.debian.org/debian-cd/current/amd64/iso-cd/debian-9.4.0-amd64-netinst.iso
HTTP/1.1 302 Found
Date: Mon, 18 Jun 2018 09:51:32 GMT
Server: Apache/2.4.29 (Unix)
Location: https://gensho.ftp.acc.umu.se/debian-cd/current/amd64/iso-cd/debian-9.4.0-amd64-netinst.iso
Cache-Control: max-age=300
Expires: Mon, 18 Jun 2018 09:56:32 GMT
Content-Type: text/html; charset=iso-8859-1

HTTP/1.1 200 OK
Date: Mon, 18 Jun 2018 09:51:32 GMT
Server: Apache/2.4.29 (Unix)
Last-Modified: Sat, 10 Mar 2018 11:56:52 GMT
Accept-Ranges: bytes
Content-Length: 305135616
Age: 228
Content-Type: application/x-iso9660-image

这表明该文件的大小为 305,135,616 字节。

您可以使用 Gawk 进行过滤,例如:

$ curl -s -L -I https://cdimage.debian.org/debian-cd/current/amd64/iso-cd/debian-9.4.0-amd64-netinst.iso | gawk -v IGNORECASE=1 '/^Content-Length/ { print $2 }'
305135616

(该-s选项指示curl不要打印进度信息,默认情况下,当其输出被重定向时,它会打印进度信息。)

请注意,此信息并不总是可用,因此您的脚本应该准备好处理该信息。

相关内容