Pesky little bash quoting problem

Have to admit it – this happens every time I sit down to write a some shell script that manipulates paths on windows (where path names often end up with spaces). Soon I find my nifty little script running into problems when it doesn’t handle spaces properly and I find myself reading up on bash quoting rules once again…

Anyway, so this post is mostly for self reference 🙂 and to put down some simple rules in the hope that writing it down will help committing it to memory.

The latest (mis)adventure was to make irfanview run under wine and a little script to allow irfanview to open a file provided on the command line. Irfanview being a windoze executable, its necessary to cd to the folder and then pass the file as argument to irfanview. Trivial isn’t it….until I found that the script fell over when it got a path liek /path/to/a folder with spaces/image.jpeg.

#! /bin/bash
DIRNAME=$(dirname “$1”)           # double quotes necessary – since $1 could have embedded spaces

FILENAME=$(basename “$1”)
cd “$DIRNAME”                               # once more, double quotes necessart
irfanview $FILENAME

Golden Rule

When passing a path as argument, always enclose in double quotes.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s