Home > Back-end >  Passing a parameter containng space character inside a command inside bash function
Passing a parameter containng space character inside a command inside bash function

Time:07-04

Problem Statement: I require to compress pdfs of my internet bills for reimbursement. For this I use the following script.

gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/ebook -dNOPAUSE -dQUIET -dBATCH -sOutputFile=com_01-Jun-2022\ to\ 30-Jun-2022.pdf Downloads/InternetBills/01-Jun-2022\ to\ 30-Jun-2022.pdf 

To make my life easier i created a bash function in bashrc which goes as follows

pdf_compress(){
  mode=$1
  in_file=$2
  in_file_name=${in_file##*/}
  out_file_name="compressed_${in_file_name}"
  gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/$mode -dNOPAUSE -dQUIET -dBATCH -sOutputFile=$out_file_name $2
}

Command run in the terminal

pdf_compress screen Downloads/InternetBills/01-Jun-2022\ to\ 30-Jun-2022.pdf

Output with Error

Error: /undefinedfilename in (to)
Operand stack:

Execution stack:
   %interp_exit   .runexec2   --nostringval--   --nostringval--   --nostringval--   2   %stopped_push   --nostringval--   --nostringval--   --nostringval--   false   1   %stopped_push
Dictionary stack:
   --dict:731/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

I can see that the spaces in filename is creating the issue. My confusion is while passing the parameter the entire relative path is taken as a single argument, but when used inside the bash function, it doesn't work. So how to use the path parameter which may contain spaces?

Any other approach which can solve this in bash is also appreciated.

CodePudding user response:

You just need to use quotes around the path.

  • Related