3

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
  • 1
    What have you tried so far? – fd0 Sep 19 '19 at 15:58
  • I dont know what to try. How would I make the script add a number to the name. Ive tried $ and then let "i++" $i and that didnt work. – FloridaGuy Sep 19 '19 at 16:04
  • 2
    Please edit your original post with the shell code that you tried to use. – fd0 Sep 19 '19 at 16:05
  • ok I added what I tried – FloridaGuy Sep 19 '19 at 16:08
  • Do you need the existing files, or do you just want to incrementally add a number to each new file you download? – nohillside Sep 19 '19 at 16:12
2

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
  • Thanks man, this fixed the issue! – FloridaGuy Sep 19 '19 at 16:15
-2

I would do this as one-liner just saving file to a new location. Can't see any reason to move files around.

i=0; while :; do curl link.com/latest.jpg -o ${i}_latest.jpg && sleep $(( 5 * 60 )) && (( i++ )); done

I suppose this script takes long time to run and to be able to close terminal or logout suggest to use nohup command

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .