Using filenames with spaces inside scripts: how to fix errors
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
- 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 (
\
). For more info about this, check Bash syntax: working with text. - Run the command with
sh
. Instead of executing the command directly, run it insidesh
, with the-c
parameter and with double quotes around (e.g.:sh -c "COMMAND"
).
Examples
#!/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'
A one-line example with a ‘for’ loop:
for i in *.pdf; do INPUT=${i// /\\ }; sh -c "some_comand -i $INPUT -o out/$INPUT";done
If you have any suggestion, feel free to contact me via social media or email.
Latest tutorials and articles:
Featured content: