Koteg
Koteg

Reputation: 497

Shell Script: Concatenate string while interating

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?

Upvotes: 1

Views: 2894

Answers (3)

user unknown
user unknown

Reputation: 36269

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]}

Upvotes: 2

dimba
dimba

Reputation: 27641

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

x = 1 # execution of x with arguments '=' and '1'
x=1   # setting shell variable x

Upvotes: 4

user184968
user184968

Reputation:

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

pdffiles=$filename' '$pdffiles

Upvotes: 2

Related Questions