I would like to write a script where I try to download a file with wget (or curl if is really not something that can be done with wget) and do 2 actions if the file exists and it's downloaded correctly or... something else if the file is not downloaded correctly or is not found/server timeout/whatever else from being downloaded correctly.

How this can be achieved? Wget | sed/grep something -> == "200".. or a compare based on filesize shown in the headers.. ? then the actions?

  • 1
    "Downloaded correctly" can be tricky -- see unix.stackexchange.com/q/271070/117549 – Jeff Schaller Mar 31 '16 at 0:30
  • 1
    You might want to add -t 1 to ensure that when wget exits ok you will find the file under the expected filename, and not for example "file.1". See JeffSchaller's link. – meuh Mar 31 '16 at 8:00
  • @meuh good pick ;) however in my script i have a fixed -O option already in so it will always overwrite a specific file without adding the .1 .2 .3 .. – user3450548 Mar 31 '16 at 8:13

Programs like wget and curl already exit with an error if the download fails. You can use a normal bash if without pipes:

if wget [...]
  echo 'Downloaded :-)'
  echo 'Error :-('
| improve this answer | |
  • This will cover any case? I mean if wget... will return true only if the file is fully downloaded without issues of any kind ? Fully downloaded file not just status 200, you know, to cover even the case my router reboots during the download! :) – user3450548 Mar 30 '16 at 23:48
  • That's how wget and any Unix & Linux program is expected to work. You can check documentation of the exit status of wget here: 0: No problems occurred. – zuazo Mar 30 '16 at 23:53
  • If your router reboots and the download is interrupted, wget will return an error. – zuazo Mar 30 '16 at 23:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.