Cómo obtener el tamaño de archivo remoto de un script de shell?


Hay una manera de obtener el tamaño de un archivo remoto como

http://api.twitter.com/1/statuses/public_timeline.json

En el script de shell?

Author: codaddict, 2010-12-21

11 answers

Puede descargar el archivo y obtener su tamaño. Pero podemos hacerlo mejor.

Uso rizo para obtener solo el encabezado de respuesta usando la opción -I.

En el encabezado de respuesta busque Content-Length: que será seguido por el tamaño del archivo en bytes.

$ URL="http://api.twitter.com/1/statuses/public_timeline.json"
$ curl -sI $URL | grep -i Content-Length
Content-Length: 134

Para obtener el tamaño use un filtro para extraer la parte numérica de la salida anterior:

$ curl -sI $URL | grep -i Content-Length | awk '{print $2}'
134
 71
Author: codaddict,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-11 09:59:43

Dos advertencias a las otras respuestas:

  1. Algunos servidores no devuelven la longitud de contenido correcta para una solicitud HEAD, por lo que es posible que deba realizar la descarga completa.
  2. Es probable que obtenga una respuesta excesivamente grande (en comparación con un navegador moderno) a menos que especifique las cabeceras gzip/deflate.

También, puede hacer esto sin grep / awk o piping:

curl 'http://api.twitter.com/1/statuses/public_timeline.json' --silent --write-out 'size_download=%{size_download}\n' --output /dev/null

Y la misma solicitud con compresión:

curl 'http://api.twitter.com/1/statuses/public_timeline.json' --silent  -H 'Accept-Encoding: gzip,deflate' --write-out 'size_download=%{size_download}\n' --output /dev/null
 14
Author: James H,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-10 08:52:54

Similar a la respuesta de codaddict , pero sin la llamada a grep:

curl -sI http://api.twitter.com/1/statuses/public_timeline.json | awk '/Content-Length/ { print $2 }'
 7
Author: Johnsyweb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:46:37

Las respuestas anteriores no funcionarán cuando haya redirecciones. Por ejemplo, si uno quiere el tamaño del DVD iso de debian, debe usar la opción location location, de lo contrario, el tamaño reportado puede ser el del cuerpo de respuesta 302 Moved Temporarily, no el del archivo real.
Supongamos que tiene la siguiente url:

$ url=http://cdimage.debian.org/debian-cd/8.1.0/amd64/iso-dvd/debian-8.1.0-amd64-DVD-1.iso

Con curl, se puede obtener:

$ curl --head --location ${url}
HTTP/1.0 302 Moved Temporarily
...
Content-Type: text/html; charset=iso-8859-1
...

HTTP/1.0 200 OK
...
Content-Length: 3994091520
...
Content-Type: application/x-iso9660-image
...

Por eso prefiero usar HEAD, que es un alias del comando lwp-request del paquete libwww-perl (en debian). Otro las ventajas que tiene es que elimina los caracteres adicionales \r, lo que facilita el procesamiento posterior de cadenas.

Así que para recuperar el tamaño del DVD iso de Debian, se podría hacer por ejemplo:

$ size=$(HEAD ${url})
$ size=${size##*Content-Length: }
$ size=${size%%[[:space:]]*}

Tenga en cuenta que:

  • este método requerirá iniciar solo un proceso
  • funcionará solo con bash, debido a la sintaxis de expansión especial utilizada

Para otras conchas, es posible que tenga que recurrir a sed, awk, grep et al..

 4
Author: ncarrier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-16 08:59:56

La solución aceptada no estaba funcionando para mí, esto es:

curl -s https://code.jquery.com/jquery-3.1.1.min.js | wc -c
 3
Author: fguillen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-08 09:33:07

Creo que la forma más fácil de hacer esto sería:

  1. Utilice cURL para ejecutar en modo silencioso -s,

  2. Tire solo de los encabezados -I (para evitar descargar todo el archivo)

  3. A continuación, haga un grep insensible a mayúsculas y minúsculas -i

  4. Y devuelve el segundo arg usando awk $2.

  5. La Salida se devuelve como bytes

Ejemplos:

curl -sI http://api.twitter.com/1/statuses/public_timeline.json | grep -i content-length | awk '{print $2}'

//output: 52

O

curl -sI https://code.jquery.com/jquery-3.1.1.min.js | grep -i content-length | awk '{print $2}'

//output: 86709

O

curl -sI http://download.thinkbroadband.com/1GB.zip | grep -i content-length | awk '{print $2}'

//output: 1073741824

Mostrar como Kilobytes / Megabytes

Si desea mostrar el tamaño en Kilobytes, cambie el awk a:

awk '{print $2/1024}'

O Megabytes

awk '{print $2/1024/1024}'
 3
Author: Andrew Odendaal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-25 23:11:24

Tengo una función de shell, basada en la respuesta de codaddict , que da el tamaño de un archivo remoto en un formato legible por humanos:

remote_file_size () {
  printf "%q" "$*"           |
    xargs curl -sI           |
    grep Content-Length      |
    awk '{print $2}'         |
    tr -d '\040\011\012\015' |
    gnumfmt --to=iec-i --suffix=B # the `g' prefix on `numfmt' is only for systems
  # ^                             # that lack the GNU coreutils by default, i.e.,
  # |                             # non-Linux systems
  # |
  # |                             # in other words, if you're on Linux, remove this
  # |                             # letter `g'; if you're on BSD or Mac, install the GNU coreutils
} # |                                        |
  # +----------------------------------------+
 0
Author: GDP2,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-31 06:11:57

Para combinar todo lo anterior para mí funciona:

URL="http://cdimage.debian.org/debian-cd/current/i386/iso-dvd/debian-9.5.0-i386-DVD-1.iso"
curl --head --silent --location "$URL" | grep -i "content-length:" | tr -d " \t" | cut -d ':' -f 2

Esto devolverá solo la longitud del contenido en bytes:

3767500800
 0
Author: Tom Freudenberg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-04 15:24:09

Uso así ([Cc]ontent-[Ll]ength:), porque tengo servidor dar múltiples caracteres de longitud de contenido en respuesta de encabezado

curl -sI "http://someserver.com/hls/125454.ts" | grep [Cc]ontent-[Ll]ength: | awk '{ print $2 }'

Accept-Ranges: bytes Access-Control-Expose-Headers: Date, Server, Content-Type, Content-Length Server: WowzaStreamingEngine/4.5.0 Cache-Control: no-cache Access-Control-Allow-Origin: * Access-Control-Allow-Credentials: true Access-Control-Allow-Methods: OPTIONS, GET, POST, HEAD Access-Control-Allow-Headers: Content-Type, User-Agent, If-Modified-Since, Cache-Control, Range Date: Tue, 10 Jan 2017 01:56:08 GMT Content-Type: video/MP2T Content-Length: 666460

 -1
Author: Fathur Rohim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-10 02:04:21

Esto le mostrará una información detallada sobre la descarga en curso

Solo necesita especificar una URL como el siguiente ejemplo.

$ curl -O -w 'We downloaded %{size_download} bytes\n' 
https://cmake.org/files/v3.8/cmake-3.8.2.tar.gz

Salida

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 7328k  100 7328k    0     0   244k      0  0:00:29  0:00:29 --:--:--  365k
We downloaded 7504706 bytes

Para fines automatizados, solo tendrá que agregar el comando a su archivo de script.

 -1
Author: Ali,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-26 00:26:01

Solución diferente:

ssh userName@IP ls -s PATH | grep FILENAME | awk '{print$1}'

Le da el tamaño en KB

 -3
Author: Ortal Turgeman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-07 13:04:40