How to create recursive download and rename bash script

bashcommand linefinderterminal

I need to make a bash script that will download a image with curl and then rename the file, wait 5 mins and then re-download the file and rename it again so that the new file does not replace the old file. I understand the wait and curl download part but I cant make the script recursively rename the new files. It would need to rename the files like: latest.jpg –> latest1.jpg and then the next one latest.jpg –> latest2.jpg. Please help!

#!/bin/bash
while true
do
    curl -O link.com/latest.jpg
    let "i++"
    mv latest.jpg $ilatest.jpg
    sleep 5m
done

Best Answer

I would change two things to make it work

  • the variable need to be put in {} to separate it from the other text (how should bash know that the variable isn't called ilatest otherwise?
  • sleep expects the sleep time in seconds

This gives you

#!/bin/bash
i=0
while true
do
    curl -O link.com/latest.jpg
    let "i++"
    mv latest.jpg latest-${i}.jpg
    sleep $((5*60))
done

In addition, having the sleep as part of the loop code will require that you press ^C twice to terminate the loop. You might want to try the following instead

#!/bin/bash
i=0
s=0
while sleep $s
do
    curl -O link.com/latest.jpg
    let "i++"
    mv latest.jpg latest-${i}.jpg
    let 's=5*60'
done