Pesky little bash quoting problem

· Read in about 1 min · (200 words) ·

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
irfanview $FILENAME

Golden Rule