Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

First of all, sorry for my english: i'm not british/american.

Here is my problem. I've got a folder named pdf with lots of files pdf inside it. I've got another folder named thumbnail, which is empty. I want to create jpg images preview of each pdf to use them in my HTML webpages as previews of the pdf.

To do this I'm using a software called IMAGEMAGICK. I tried to put the code inside my PHP files to get the purpose, but it doesn't work. As you understood, I have created a small search engine with apache, mysql to search for pdf locally (offline). Now I want to add a "preview" of the first page of pdfs. Instead, it works by bash command line and the code is:

convert pdf/name_of_the_file_pdf.pdf[0] name_of_the_imagefile.jpg

(The zero stands for that the image is taken from the FIRST page of pdf) How can i make a script that takes each name of pdf files and put it into that code???? To list all the file, I did

ls >pdf

but with the little knowledge I have I can't go further.... Some pdf's names contain spaces....Is that a problem?

PDF files are so many that i can't do the task typing every name,it wouldn't be a nice and clever work!!!! Thanks a lot in advance!!!

share|improve this question
up vote 3 down vote accepted

Any solution that uses the ls command will eventually fail, but don't fret; bash can handle any and all filenames safely without involving an external command (like ls) to "list" them.

To make a filename.jpg from every filename.pdf in the current directory, you can do:

for file in ./*.pdf; do
    convert "$file[0]" "${file%.pdf}.jpg"

You can also do that in one line

for file in ./*.pdf; do convert "$file[0]" "${file%.pdf}.jpg"; done

The double quotes (") are very important to avoid wordsplitting and pathname expansion from the result of the parameter expansions.

$file and ${file%.pdf} are called parameter expansions. See and for more on parameter expansions and string manipulation in bash in general.

EDIT: And reading the question again, I see you wanted the jpegs in the parent directory of the pdfs, so I'll include the necessary modifications for that as well:

for file in pdf/*.pdf; do
    convert "$file[0]" "./${basename%.pdf}.jpg"
share|improve this answer

Your Answer


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.