쉘 스크립트가 순서대로 실행되지 않는 이유는 무엇입니까? (아마도 imagemagick?)

쉘 스크립트가 순서대로 실행되지 않는 이유는 무엇입니까? (아마도 imagemagick?)

나는 디렉토리의 각 파일에 대해 세 개의 imagemagick 명령을 실행하는 간단한 bash 쉘 스크립트를 만들었습니다. 각 명령을 동시에 실행하기 위해 &나 |를 사용하지 않았습니다.

#!/bin/bash


jpg="$1/*.jpg"
jpeg="$1/*.jpeg"
JPG="$1/*.JPG"
png="$1/*.png"
#convert to png
to_png() {
    for file in $jpg; do mogrify -format png $file; rm $file; done
    for file in $jpeg; do mogrify -format png $file; rm $file; done
    for file in $JPG; do mogrify -format png $file; rm $file; done
}

#format for 4k
to_4k() {
    for file in $png; do convert $file -resize 3840x2160 $file; done
}

#put on transparent background
to_trans() {
    for file in $png; do composite -gravity center $file -geometry 3840x2160 /path/to/transparent/background $file; done
}

do_stuff() {

    to_png
    to_4k
    to_trans

}

if [ -d "$1" ];
then do_stuff
else echo "You didn't enter a directory. Please try again."
fi

디렉터리에 .jpg 파일이 있으면 오류 메시지가 나타납니다. ImageMagick은 파일이 완료되기 전에 bash에게 명령이 완료되었음을 알려줍니까?

convert: Expected 8 bytes; found 0 bytes `/path/to/picture/image.png' @ warning/png.c/MagickPNGWarningHandler/1669.
convert: Read Exception `/path/to/picture/image.png' @ error/png.c/MagickPNGErrorHandler/1643.
convert: corrupt image `/path/to/picture/image.png' @ error/png.c/ReadPNGImage/3973.
convert: no images defined `/path/to/picture/image.png' @ error/convert.c/ConvertImageCommand/3210.
composite: Expected 8 bytes; found 0 bytes `/path/to/picture/image.png' @ warning/png.c/MagickPNGWarningHandler/1669.

명령 사이에 긴 절전 모드를 사용하면 이 문제를 해결할 수 있지만 매우 엉성합니다.

참고 사항: for 루프에서 $1/*.jpg를 사용하면 분명히 $1 및 *가 확장되지 않기 때문에 디렉토리를 변수에 저장하고 있습니다. Bash는 /path/to/*.jpg가 존재하지 않는다는 오류를 반환합니다.

저는 Ubuntu 16.04(x86_64), GNU bash 4.3.48 및 ImageMagick 6.8.9-9를 사용하고 있습니다.

답변1

$1내부 기능은 외부 기능과 다릅니다 $1.

dir="$1"따라서 스크립트 start: , ... 에 저장 하고 $dir다른 곳에서 사용해야 합니다.

이렇게 하면 스스로 발견한 첫 번째 이상한 문제(bash: 경로가 존재하지 않음)를 해결할 수 있지만... 아마도 다른 모든 문제는 해결될 것입니다.

해결 방법이 불완전합니다. 변수를 따옴표로 묶어야 하지만 전역 확장이 잘못됩니다... 스크립트의 단순화된 버전은 확실히 잘 작동하므로 코드를 정리하는 것뿐입니다.

#!/bin/bash

shopt -s nullglob ; set -o xtrace           #xtrace for debug
dir="$1" ; [ -d "$dir" ] || dir=.
for file in "$dir"/*.{jpg,jpeg,JPG}; do mogrify -format png "$file"; rm "$file"; done
for file in "$dir"/*.png; do convert "$file" -resize 3840x2160 "$file"; done
for file in "$dir"/*.png; do composite -gravity center "$file" -geometry 3840x2160 /home/d/bin/youtube_tools/4kclear.png "$file"; done

관련 정보