5

When converting an image, ImageMagick's default behavior seems to be to overwrite any existing file. Is it possible to prevent this? I'm looking for something similar to Wget's --no-clobber download option. I've gone through ImageMagick's list of command-line options, and the closest option I could find was -update, but this can only detect if an input file is changed.

Here's an example of what I'd like to accomplish: On the first run, convert input.jpg output.png produces an output.png that does not already exist, and then on the second run, convert input.jpg output.png detects that output.png already exists and does not overwrite it.

oronymzy
  • 59
  • 1
  • 5
  • 1
    It's like most programs from the Unix world - it kind of assumes you know what you are doing. It's more like a Windows approach to ask if you really meant what you typed. I guess it's just a different ethos. – Mark Setchell Dec 30 '18 at 22:05
  • 1
    You can script a test if the file exists or not and then do your convert as desired. That is easy in Unix bash for example. See https://www.shellhacks.com/bash-test-if-file-exists/ – fmw42 Dec 31 '18 at 00:50

2 Answers2

2

Just test if it exists first, assuming bash:

[ ! -f output.png ] && convert input.png output.png

Or slightly less intuitively, but shorter:

[ -f output.png ] || convert input.png output.png
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
0

Does something like this solve your problem?

It will write to output.png but if the file already exists a new file will be created with a random 5 character suffix (eg. output-CKYnY.png then output-hSYZC.png, etc.).

convert input.jpg -resize 50% $(if test -f output.png; then echo "output-$(head -c5 /dev/urandom | base64 | tr -dc 'A-Za-z0-9' | head -c5).png"; else echo "output.png"; fi)
Molomby
  • 5,859
  • 2
  • 34
  • 27
  • 2
    To generate a random name you could use `mktemp output-XXXXX.png` instead of `/dev/urandom`. This is easier and also checks that the random name is unused. – Socowi Aug 03 '21 at 09:43