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

San*_*osh 8 linux size shell-script curl

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

谁能帮我这个?

Ste*_*itt 13

使用该-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
Run Code Online (Sandbox Code Playgroud)

这表明该文件的大小为 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
Run Code Online (Sandbox Code Playgroud)

(该-s选项告诉curl不打印进度信息,默认情况下它会在其输出重定向时执行此操作。)

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

  • 您可以用 numfmt 包裹它以使其可读: numfmt --to=iec-i --suffix=B $(curl -s -L -I https://cdimage.debian.org/debian-cd/ current/amd64/iso-cd/debian-10.4.0-amd64-netinst.iso | awk 'BEGIN{RS="\r\n"} /^Content-Length/ { print $2 }')`: `336MiB` (3认同)