Search code examples
linuxbashpdfjpeg

bash shell script command substitution problem - escape basefile name spaces - multiple pdf files to jpeg conversion using ghostscript


This bash shell script takes multiple .pdf file inputs using zenity and stores in an array for ghostscript .pdf to .jpeg conversion.

Problem

  1. need the file path stored in array with escaped spaces to go into the gs command $i
  2. need the basefile name for output filename in gs command inside for loop
  3. gs command needs file names with spaces escaped.
  4. unable to run the gs command error command not found on line 20.

Code:

#get list of selected files from Graphical Dialog
listOfFilesSelected=$(zenity --file-selection --multiple --filename "${HOME}/")
#echo $listOfFilesSelected

# Here pipe is our delimiter value
IFS="|" read -a listFiles <<< $listOfFilesSelected

#echo "File: ${listFiles[@]}"
# get length of an array
#arraylength=${#listFiles[@]}

#echo "${listFiles[0]}"
##echo $'\n'
#echo "Number of elements in the array: ${#listFiles[@]}"


 for i in "${listFiles[@]}"
     do
         echo $i
         baseFileName = $(basename '$i')
         echo $baseFileName

         gs -dNOPAUSE -sDEVICE=jpeg -sOutputFile=output%d.jpg -dJPEGQ=100 -r600 -q $i -c quit
     done

Output: Error

/home/q/Downloads/FinalAnsKey22COMPUTER SCIENCE.pdf
./zentest.sh: line 20: baseFileName: command not found

Error: /undefinedfilename in (/home/q/Downloads/FinalAnsKey22COMPUTER)
Operand stack:

Execution stack:
   %interp_exit   .runexec2   --nostringval--   --nostringval--   --nostringval--   2   %stopped_push   --nostringval--   --nostringval--   --nostringval--   false   1   %stopped_push
Dictionary stack:
   --dict:732/1123(ro)(G)--   --dict:0/20(G)--   --dict:75/200(L)--
Current allocation mode is local
Last OS error: No such file or directory
GPL Ghostscript 9.50: Unrecoverable error, exit code 1

Solution

  • As commented by others, you need to double-quote variables especially when the filenames in the variable contain whitespaces.

    Would you please try instead:

    #!/bin/bash
    
    listOfFilesSelected=$(zenity --file-selection --multiple --filename "${HOME}/")
    
    IFS="|" read -ra listFiles <<< "$listOfFilesSelected"
    
    for i in "${listFiles[@]}"; do
        echo "$i"
        baseFileName=$(basename "$i")
        echo "$baseFileName"
    
        gs -dNOPAUSE -sDEVICE=jpeg -sOutputFile="$baseFileName"%d.jpg -dJPEGQ=100 -r600 -q "$i" -c quit
    done