在Bash shell脚本中处理Imagemagick错误

问题描述 投票:0回答:2

我正在运行一个shell脚本,它循环超过12,000个图像,将每个图像与另一个目录中的双图像进行比较。问题是当双胞胎图像不存在时,Imagemagick就会死亡并报告错误,但我无法处理它以对错误进行日志记录。

代码我尝试:

#!/bin/bash

compare -metric AE -fuzz 1% /opt/fotos/239413.bmp /opt/fotos/549005.bmp -compose Src imgdiff.bmp
result="$?"

if [ "$result" -ne 0 ]; then
    echo "Your command exited with non-zero status $result"
fi

exit 0

这就是问题所在,因为ImageMagick会返回

compare-im6.q16: image widths or heights differ `/opt/fotos/239413.bmp' @ error/compare.c/CompareImageCommand/1000.

现在,我期待$ result包含该字符串,但bash期待0-255。只是为了让你知道命令本身是完美的,当图像在那里比较时返回不同的像素数,以便命令按照需要工作。

只是在发生错误并且Imagemagick死亡时。那我在哪里错了?

bash shell imagemagick
2个回答
0
投票

我没有看到你的日志文件,所以我假设它是$ logfile。通过捕获stderr保存错误消息:

tmpfile=$(mktemp /tmp/myscript.err.XXXXXX)
compare -metric AE -fuzz 1% /opt/fotos/239413.bmp /opt/fotos/549005.bmp -compose Src imgdiff.bmp 2>"$tmpfile"

result="$?"

if [ "$result" -ne 0 ]; then
    echo "Your command exited with non-zero status $result"
    cat "$tmpfile" >> $logfile
fi
rm "$logfile"

exit 0

或者如果你真的想要结果包含字符串,请使用

result=`cat "$logfile"`

0
投票

希望我将用作我的解决方案基础的以下代码将解释我想要做的事情。我测试了这个并且它正在做我想要的但是我必须提到我正在考虑实现用户fmw42建议的内容,但是现在将采用这种方式。

是的,我知道这些消息可能会改变,但会根据需要处理它们。希望这有助于某人。

#!/bin/bash

compare_result=$(compare -metric AE -fuzz 1% /opt/fotos/239413A.bmp /opt/fotos/54900343.bmp -compose Src imgdiff.bmp 2>&1)

if echo "$compare_result" | grep -q "No such file or directory @"; then
    echo "No such file or directory was returned handle accordingly."
    exit 1
fi

if ! [[ "$compare_result" =~ ^[0-9]+$ ]]; then
    echo "Compare returned an invalid integer: $compare_result"
    exit 1
fi

echo "The final result was: $compare_result"

exit 0
© www.soinside.com 2019 - 2024. All rights reserved.