Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the file is downloaded with curl

I am writing a shell script, I need to download 6 files from internet, In the script I have done it as

curl a
curl b
curl c
and so on

It works, but sometimes curl: (7) couldn't connect to host for some files in the middle of script for example, It will successfully download a but miss the file b with the above error and will download the file c. I would like to catch this error so that my code will execute with the successful download of all the files.

like image 874
ashishk Avatar asked May 28 '16 19:05

ashishk


People also ask

How do you check if files are being downloaded?

To find downloads on your PC, select File Explorer from the taskbar, or press the Windows logo key + E. Under Quick access, select Downloads. You can also find your Downloads folder under This PC. To see where your browser is saving downloads, look in your browser's settings.

Does curl download file?

One can use curl to download file or transfer of data/file using many different protocols such as HTTP, HTTPS, FTP, SFTP and more. The curl command line utility lets you fetch a given URL or file from the bash shell.

Where does curl save downloaded files?

The file will be saved to the current directory that you are working in. To save the file in a different directory, change the working directory before running the Curl command. If the file already exists, it will be overwritten.

Does curl resume download?

cURL and Wget are popular web interface command line utilities that among their many features can resume interrupted or canceled downloads. cURL is a library with a command-line frontend, while Wget is a command line tool.


1 Answers

You can use a loop:

while true; do
  curl --fail b && break
done

The loop won't break until b is downloaded. You can make it a retry function which you can call if a download fails on the first try:

retry(){
    while true; do
      curl --fail "$1" && break ||
      echo "Download failed for url: $1
            retrying..."
    done
}

Then do this:

curl --fail a || retry a
curl --fail b || retry b
curl --fail c || retry c

If you just want to silent the error messages then:

curl a 2>/dev/null
curl b 2>/dev/null
...

Or if you want to just detect the error then:

if ! curl --fail a; then
  echo "Failed"
fi

or, a one liner:

curl --fail a || echo Failed

If you want to exit after a failure and also show your own message:

curl --fail a 2>/dev/null || { echo failed; exit 1; }
like image 118
Jahid Avatar answered Nov 09 '22 23:11

Jahid