My IP camera saves a video (.mp4 file) and a picture (.jpg file) every minute to my Pi, which is set up as an FTP server.

I want to open the latest picture with ImageMagick every 5 minutes.

The filename contains a timestamp, so I don't know how to call the JPEG file in a terminal command. The filename looks like this: 01_20160719210835.jpg.  I can find the newest filename in the folder by doing a cd into the folder and running ls -t *.jpg | head -1.  But how can I open an image in ImageMagick based on this?

Also, how can I delete the .mp4s hourly?

  • 1
    I don’t understand your second question. Do you know how to use cron (i.e., how to use crontab)? Would running rm *.mp4 hourly via cron answer your question? – G-Man Says 'Reinstate Monica' Jul 19 '16 at 23:53

I have never used ImageMagick, so I don’t know what its commands are.  I presume/hope that you know how to open a file given its name.  (I can imagine that it might be something trivial and straightforward like imagemagick filename or open filename.)

You’re almost there: you should be able to do what you want with

command "$(ls -t *.jpg | head -1)"


  • The quotes are an important part of the answer.
  • This will fail if you have filename(s) with newline(s) in them.
  • This can fail if you have a directory with a name that ends with .jpg.

this is my script to add my logo to the latest image and remove all video files, i run it via cron every 5 minutes

cd /mnt/dietpi_userdata/webcam/dump
composite -geometry +30+10 /mnt/dietpi_userdata/webcam/logo.png "$(ls -t *.jpg | head -1)" /mnt/dietpi_userdata/webcam/webcam.jpg

convert /mnt/dietpi_userdata/webcam/webcam.jpg -gravity North -pointsize 40 -annotate +30+10 'my homepage' /mnt/dietpi_userdata/webcam/webcam.jpg

rm /mnt/dietpi_userdata/webcam/dump/*.mp4

thx for the help


What do you want to do with ImageMagick? If you just want to display the image and sort by the timestamp in the filename, you can do this:

display "$(ls *.jpg | sort -k1.4 | tail -1)"

The parameter -k1.4 makes it to be sorted by the fourth character (ignore 01_ in the beginning).

  • Note that ls can already sort on time (e.g. ls -lart). – Hennes Jul 21 '16 at 19:15
  • Yes, the other answers use ls to sort. I just wanted to show another way, which uses the file name. – Marco Jul 21 '16 at 22:11

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.