Home > Enterprise >  Bash script variables not expanding as expected for ghost script command
Bash script variables not expanding as expected for ghost script command

Time:10-27

I want to combine two pdf's content.pdf and another.pdf into a single output.pdf file. If I do:

FILES=("content.pdf" "another.pdf")
gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile="output.pdf" -dAutoRotatePages=/None $(printf "'%s' " "${FILES[@]}")

I'll get an error:

Error: /undefinedfilename in ('content.pdf')

But if I echo the same command instead:

echo "gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile="output.pdf" -dAutoRotatePages=/None $(printf "'%s' " "${FILES[@]}")"

And copy-paste the output directly to terminal:

gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=output.pdf -dAutoRotatePages=/None 'content.pdf' 'another.pdf'

The command works. What am I missing here?

CodePudding user response:

The filename arguments are passed to the gs command surrounded with single quotes. That is, the command sees them as literal ' characters (as part of the filename). You should delete 's around the %s in printf's format string or you shouldn't use printf and command substitution at all. Simply

gs …options… "${FILES[@]}"

should work. Note that deleting 's around the %s won't work properly when filenames contain whitespace characters (or glob characters which may match existing filenames).

  •  Tags:  
  • bash
  • Related