Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I want to write a bash script to convert every .pdf file in the current directory into a .png file. For example:

$ls .
a.pdf b.pdf
$./pdf2png.sh
Converting pdfs to pngs
a.pdf -> a.png
b.pdf -> b.png

This is my best attempt:

#!/bin/bash
convert -verbose -density 500 -resize '800' a.pdf a.png
convert -verbose -density 500 -resize '800' b.pdf b.png
share|improve this question

2 Answers 2

up vote 4 down vote accepted

If you have really strange names, ones that contain newlines or backslashes and the like, you could do something like this:

find . -type f -name '*.pdf' -print0 |
  while IFS= read -r -d '' file
    do convert -verbose -density 500 -resize 800 "${file}" "${file%.*}.png"
  done

That should be able to deal with just about anything you throw at it.

Tricks used:

  • find ... -print0 : causes find to print its results separated by the null character, let's us deal with newlines.
  • IFS= : this will disable word splitting, needed to deal with white space.
  • read -r: disables interpreting of backslash escape characters, to deal with files that contain backslashes.
  • read -d '': sets the record delimiter to the null character, to deal with find's output and correctly handle file names with newline characters.
  • ${file%.*}.png : uses the shell's inbuilt string manipulation abilities to remove the extension.
share|improve this answer
    
Both answers are good but I accepted this one because it comes with an explanation of the tricks used. –  I Like to Code Mar 25 at 14:13

You can use bash for loop as follows:

#!/bin/bash
for pdfile in *.pdf ; do
  convert -verbose -density 500 -resize '800' "${pdfile}" "${pdfile%.*}".png
done
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.