[英]Handling Imagemagick error in Bash shell script
我正在运行一个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死亡时。 那我在哪里错了?
我看不到您的日志文件,因此我假设它是$ 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"`
希望以下将用作解决方案基础的代码可以解释我正在尝试做的事情。 我对此进行了测试,它正在执行我想要的操作,但是我必须提到,我正在考虑实现用户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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.