I'm having a nightmare trying to get this to run correctly. I have done it fine using php code but the issue is with lots of files the command times out. I thought i could do this easily via ssh on the box itself but i can't get it to do what i want.
in PHP i'm doing the following:
$command='/usr/bin/convert "'. $LocalPDFURL . '[1]" -quality 70% "' . $LocalJPGURL . '"' ;
I need to search for pdf files, check if they have a .jpg with the same file name if not generate a jpg using the first page of the pdf. The above works fine in php. But in linux shell script it won't work no matter what i've tried. I've tried all sorts of combinations it just either outputs the whole thing as a string or errors as it's not passed the double quotes required to specify the full file paths (they contain spaces).
My script is this:
format=*.pdf
wpath=$format
for i in $wpath;
do
if [[ "$i" == "$format" ]]
then
echo "No PDF Files to process!"
else
echo "full file name: $i"
FILE="${i%.pdf}.jpg"
if [ -f "$FILE" ]; then
echo "$FILE exists."
else
ORIGINAL=\""${FILE%.jpg}.pdf\""
QFILE=\""$FILE%\""
echo "$FILE does not exist. Creating PDF Cover JPG!"
command="/usr/bin/convert "\""$ORIGINAL"\" 1 -quality 65% $QFILE 2>&1"
echo $command
fi
fi
done
I just want to build the command and execute it.
The php command output looks like this...
"/usr/bin/convert "/home/test/1.pdf" 1 -quality 65% "/home/test/1.jpg" 2>&1"
and runs fine.
I've tried single quotes, double quotes escaping them etc. Please someone help!
So my advice is the following:
maybe_convert(){
! [ -f "${1%.*}.jpg" ] && echo "/usr/bin/convert \"$1\" 1 -quality 65% \"${1%.*}.jpg\"" || echo $1 exists
}
export -f maybe_convert
find . -type f -name "*.pdf" | xargs -I{} bash -c "maybe_convert \"{}\""
The snippet above works for the following file structure (assuming thet you have saved the snippet in a file named convert_image.sh
):
$ ls testdir/
'file 1.jpg' 'file 1.pdf' 'file 2.pdf' 'file 3.pdf'
$ bash convert_image.sh
/usr/bin/convert "./testdir/file 3.pdf" 1 -quality 65% "./testdir/file 3.jpg"
/usr/bin/convert "./testdir/file 2.pdf" 1 -quality 65% "./testdir/file 2.jpg"
./testdir/file 1.pdf exists