Nice programing

쉘 스크립트에서 원격 파일 크기를 얻는 방법은 무엇입니까?

nicepro 2020. 11. 30. 19:53
반응형

쉘 스크립트에서 원격 파일 크기를 얻는 방법은 무엇입니까?


다음과 같은 원격 파일의 크기를 얻는 방법이 있습니까?

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

쉘 스크립트에서?


파일을 다운로드하고 크기를 확인할 수 있습니다. 하지만 우리는 더 잘할 수 있습니다.

옵션을 사용하여 응답 헤더 만 가져 오려면 curl사용하십시오 .-I

응답 헤더 Content-Length:에서 파일 크기 (바이트)가 뒤에 오는 것을 찾으십시오 .

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

크기를 얻으려면 필터를 사용하여 위의 출력에서 ​​숫자 부분을 추출하십시오.

$ curl -sI $URL | grep -i Content-Length | awk '{print $2}'
134

다른 답변에 대한 두 가지주의 사항 :

  1. 일부 서버는 HEAD 요청에 대해 올바른 Content-Length를 반환하지 않으므로 전체 다운로드를 수행해야 할 수 있습니다.
  2. gzip / deflate 헤더를 지정하지 않으면 최신 브라우저에 비해 비현실적으로 큰 응답을받을 수 있습니다.

또한 grep / awk 또는 파이핑없이이 작업을 수행 할 수 있습니다.

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

압축과 동일한 요청 :

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

유사 codaddict의 대답 하지만, 호출하지 않고 grep:

curl -sI http://api.twitter.com/1/statuses/public_timeline.json | awk '/Content-Length/ { print $2 }'

리디렉션이있는 경우 이전 답변이 작동하지 않습니다. 예를 들어 데비안 iso DVD의 크기를 원하면 --location 옵션을 사용해야합니다. 그렇지 않으면보고 된 크기가 302 Moved Temporarily실제 파일이 아닌 응답 본문 의 크기 일 수 있습니다 .
다음 URL이 있다고 가정합니다.

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

curl을 사용하면 다음을 얻을 수 있습니다.

$ 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
...

그렇기 때문에 libwww-perl 패키지 (debian에서) HEADlwp-request명령에 대한 별칭 인을 사용하는 것을 선호합니다 . 또 다른 장점은 추가 \ r 문자를 제거하여 후속 문자열 처리를 용이하게 한다는 것 입니다.

따라서 데비안 iso DVD의 크기를 검색하려면 다음과 같이 할 수 있습니다.

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

점에 유의하시기 바랍니다:

  • 이 방법은 하나의 프로세스 만 시작하면됩니다.
  • 특수 확장 구문이 사용되기 때문에 bash에서만 작동합니다.

다른 쉘의 경우 sed, awk, grep et al.을 사용해야 할 수도 있습니다.


허용되는 솔루션이 저에게 효과가 없었습니다.

curl -s https://code.jquery.com/jquery-3.1.1.min.js | wc -c

이 작업을 수행하는 가장 쉬운 방법은 다음과 같습니다.

  1. cURL을 사용하여 자동 모드로 실행하십시오 -s.

  2. 헤더 만 가져 오기 -I(전체 파일 다운로드를 방지하기 위해)

  3. 그런 다음 대소 문자를 구분하지 않는 grep을 수행하십시오. -i

  4. awk를 사용하여 두 번째 인수를 반환합니다 $2.

  5. 출력은 다음과 같이 반환됩니다. bytes

예 :

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

//output: 52

또는

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

//output: 86709

또는

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

//output: 1073741824

킬로바이트 / 메가 바이트로 표시

크기를 킬로바이트로 표시하려면 awk를 다음과 같이 변경하십시오.

awk '{print $2/1024}'

또는 메가 바이트

awk '{print $2/1024/1024}'

codaddict의 답변을 기반으로 한 쉘 기능이 있습니다. 이는 원격 파일의 크기를 사람이 읽을 수있는 형식으로 제공합니다.

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
} # |                                        |
  # +----------------------------------------+

To combine all the above for me works:

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

This will return just the content length in bytes:

3767500800

I use like this ([Cc]ontent-[Ll]ength:), because I got server give multiple Content-Length character at header response

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


This will show you a detailed info about the ongoing download

you just need to specify an URL like below example.

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

output

  % 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

For automated purposes you'll just need to add the command to your script file.


different solution:

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

gives you the size in KB

참고URL : https://stackoverflow.com/questions/4497759/how-to-get-remote-file-size-from-a-shell-script

반응형