If you’ve created a script that gets filenames as input (or output), you may have errors because the filenames are getting separated inside the script. In this ‘quick-tip’, you’ll find one way to solve this.

Table of Contents

Steps

  1. Add a backslash to escape spaces. Even if you have added a backslash character (\) before each space, inside the script the filename is parsed without the backslash. Assuming that filenames are the first and second script arguments, you can add this:
      INPUT=${1// /\\ }
      OUTPUT=${2// /\\ }
    

    This is a special Bash syntax that replaces a space character ( ) with a backslash and a space (\ ). For more info about this, check Bash syntax: working with text.

  2. Run the command with sh. Instead of executing the command directly, run it inside sh, with the -c parameter and with double quotes around (e.g.: sh -c "COMMAND").

Example

#!/bin/bash

INPUT1=${1// /\\ }
INPUT2=${2// /\\ }
OUTPUT=${3// /\\ }

sh -c "pdfunite $INPUT1 $INPUT2 $OUTPUT"

If the script is called myscript, you can run:

./myscript file1\ with\ spaces.pdf file2\ with\ spaces.pdf output\ also\ with\ spaces.pdf
./myscript 'file1 with spaces.pdf' 'file2 with spaces.pdf' 'output also with spaces.pdf'

If you have any suggestion, feel free to contact me via social media or email.