11

I have a bash beginner problem:
My path to be created is /Volumes/ADATA\ UFD/Programming/Qt, where /Volumes/ADATA\ UFD exists already. I'd like to write a script in the following form:

# create a single output directory 
outputdir="/Volumes/ADATA\ UFD/Programming/Qt"
mkdir -pv $outputdir

My problem is that mkdir creates the directory /Volumes/ADATA and ./UFD/Programming instead of creating /Volumes/ADATA\ UFD/Programming/Qt.

I have looked at this question on SO; however, none of these solutions worked:

outputdir=/Volumes/"ADATA\ UFD/Programming/Qt"
mkdir -pv $outputdir

outputdir=/Volumes/'ADATA\ UFD/Programming/Qt'
mkdir -pv $outputdir

outputdir='/Volumes/ADATA\ UFD/Programming/Qt'
mkdir -pv $outputdir

outputdir=/Volumes/ADATA' 'UFD/Programming/Qt
mkdir -pv $outputdir

What am I doing wrong? What is the good combination here?

Community
  • 1
  • 1
Barney Szabolcs
  • 11,846
  • 12
  • 66
  • 91

2 Answers2

20

You need to quote the variables when you use them. Expanded variables undergo wordsplitting. It's good practice to always quote your expansion, regardless of whether or not you expect it to contain special characters or spaces. You also do not need to escape spaces when quoting.

The following will do what you want:

outputdir='/Volumes/ADATA UFD/Programming/Qt'
mkdir -pv "$outputdir"
jordanm
  • 33,009
  • 7
  • 61
  • 76
15

Double quotes around the variable when passed to the mkdir command:

mkdir -pv "$outputdir"
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • His variable assignments are also incorrect, as they will result in a literal '\' in the filename. – jordanm Dec 05 '12 at 22:45
  • Since he says he wants the backslash in the name, he _can_ do it, though he probably _shouldn't_ do it. I noted that in a comment to the question rather than in my answer, though. – Jonathan Leffler Dec 05 '12 at 22:47