Handling Parameters with Blanks

Problem

You wrote a script that took a filename as a parameter and it seemed to work, but then one time your script failed. The filename, it turns out, had an embedded blank.

Solution

You’ll need to be careful to quote any shell parameters that might contain filenames. When referring to a variable, put the variable reference inside double quotes.

Discussion

Thanks a lot, Apple! Trying to be user friendly, they popularized the concept of space characters as valid characters in filenames, so users could name their files with names like My Report and Our Dept Data instead of the ugly and unreadable MyReport and Our_Dept_Data. (How could anyone possibly understand what those old-fashioned names meant?) Well, that makes life tough for the shell, because the space is the fundamental separator between words, and so filenames were always kept to a single word. Not so anymore.

So how do we handle this?

Where a shell script once had simply ls -l $1, it is better to write ls -l "$1" with quotes around the parameter. Otherwise, if the parameter has an embedded blank, it will be parsed into separate words, and only part of the name will be in $1. Let’s show you how this doesn’t work:

$ cat simpls.sh
# simple shell script
ls -l ${1}
$
$ ./simple.sh Oh the Waste
ls: Oh: No such file or directory
$

When we don’t put any quotes around the filename as we invoke the script, then bash sees three arguments and substitutes the first argument (Oh) for $1. The ls command runs with ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.