1

I am writing a shell script that iterates over directory content and searches for pdf files and creates a string listing all pdf files in it e.g. "pdffile1.pdf pdffile2.pdf pdffile3.pdf".

pdffiles=""

#get files in pdf directory
for filename in $1/*; do
    fn=$(basename "$filename")
    #check if file exist
    if [ -f "$filename" ]; then
        #grab only pdf files
        if [ ${filename: -4} == ".pdf" ]; then
            pdffiles = $filename $pdffiles
        fi
    fi
done

The thing is this code pdffiles = $filename $pdffiles is wrong and shell script outputs following error message ./mergepdfs.sh: line 39: pdffiles: command not found. What is wrong with that line?

1
  • Why not just: pdffiles=$( cd $1 && ls *.pdf 2> /dev/null )? Commented Feb 15, 2012 at 12:30

3 Answers 3

4

Don't use spaces around '=' when assigning:

x = 1 # execution of x with arguments '=' and '1'
x=1   # setting shell variable x
Sign up to request clarification or add additional context in comments.

Comments

2

Why not simply:

pdffiles=$1/*.pdf

If you like to get them in array form:

pdffiles=($1/*.pdf)

Output all:

 echo ${pdffiles[*]}

Output size:

 echo ${#pdffiles[*]}

Output a single name:

 echo ${pdffiles[4]}

2 Comments

To append to an array, you can use pdffiles+=("$filename")
Note that assignment is not a normal shell command and therefore it is not tokenized by splitting it into words at spaces and tabs. There is no = command to be called to handle this. In fact, you can prefix any command with name=val followed by at least one space. So roughly, 1) the line is tokenized on whitespace, 2) tokens are examined for an = expression. 3) if an = is there the token is evaluated and discarded. 4) if no = then the token is treated as a command and the other tokens are all arguments to that command.
2

I think you don't need space around =. This must be a correct line:

pdffiles=$filename' '$pdffiles

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.