Search code examples
bashspacepdftk

spaces in bash scripts


So, I've been trying for a while and this really won't work. I'm trying to write a script that will concatenate many pdf files into one without the tedium of specifying them at the command-line interface (they all have similar names).

#!/bin/bash 

i=1 
list="science.pdf" 
outputfile="file.pdf" 

while [ $i -le 3 ]; do 
    file="science (${i}).pdf" 
    list="$list $file" 
    let i=i+1 
done 

pdftk $list cat output $outputfile

And this is my output:

sean@taylor:~/Downloads/understanding/s0$ ./unite.sh 
Error: Failed to open PDF file: 
   science
Error: Failed to open PDF file: 
   (1).pdf
Error: Failed to open PDF file: 
   science
Error: Failed to open PDF file: 
   (2).pdf
Error: Failed to open PDF file: 
   science
Error: Failed to open PDF file: 
   (3).pdf
Errors encountered.  No output created.
Done.  Input errors, so no output created.

I figure that somehow the script thinks that the files should be split up wherever therre's a space, but I've tried both a backslash before the space (\ ) and surrounding the file name with a quote (\") to no avail.

Can anyone help please?


Solution

  • Don't append the filenames to a string. Use an array instead:

    i=1 
    list=( "science.pdf" )
    outputfile="file.pdf" 
    
    while [ $i -le 3 ]; do 
        file="science (${i}).pdf" 
        list+=( "$file" )
        let i=i+1 
    done 
    
    pdftk "${list[@]}" cat output $outputfile
    

    You can also simplify your script further by using a for-loop as shown below:

    list=( "science.pdf" )
    for (( i=1; i<=3; i++ )); do
        file="science (${i}).pdf"
        list+=( "$file" )
    done
    pdftk "${list[@]}" cat output $outputfile