oronymzy
oronymzy

Reputation: 61

Can ImageMagick be prevented from overwriting an existing image?

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.

Upvotes: 6

Views: 4492

Answers (2)

Mark Setchell
Mark Setchell

Reputation: 207465

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

Read it like this... ”either it exists, or (if not), create it”

Upvotes: 3

Molomby
Molomby

Reputation: 6579

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)

Upvotes: 0

Related Questions