This bash shell script takes multiple .pdf file inputs using zenity and stores in an array for ghostscript .pdf to .jpeg conversion.
Problem
- need the file path stored in array with escaped spaces to go into the gs command $i
- need the basefile name for output filename in gs command inside for loop
- gs command needs file names with spaces escaped.
- 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
CodePudding user response:
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
CodePudding user response:
Here is a fixed version of your script, check carefully I fixed multiple errors:
I recommend you check your scripts with https://shellcheck.net/
It is a static-analysis for shell scripts, that will greatly help you spotting errors, and usually lists you some options to fix it.
#!/usr/bin/env bash
#get list of selected files from Graphical Dialog
mapfile -t listFiles < <(
zenity --separator=$'\n' --file-selection --multiple --filename="$HOME/"
)
for filePath in "${listFiles[@]}"; do
printf '%s\n' "$filePath"
baseFileName=${filePath##*/}
printf '%s\n' "$baseFileName"
# remove the echo if it does what you want
echo gs -dNOPAUSE -sDEVICE=jpeg -sOutputFile=output%d.jpg -dJPEGQ=100 -r600 -q "$filePath" -c quit
done
