Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do mkdir with a path that has spaces?

Tags:

bash

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?

like image 591
Barney Szabolcs Avatar asked Dec 05 '12 22:12

Barney Szabolcs


People also ask

How do you set a path with spaces?

Use quotation marks when specifying long filenames or paths with spaces. For example, typing the copy c:\my file name d:\my new file name command at the command prompt results in the following error message: The system cannot find the file specified. The quotation marks must be used.

How do you create directories files with spaces in their name?

There are two main ways to handle such files or directories; one uses escape characters, i.e., backslash (\<space>), and the second is using apostrophes or quotation marks.

How do I handle a space in a bash path?

To cd to a directory with spaces in the name, in Bash, you need to add a backslash ( \ ) before the space. In other words, you need to escape the space.

How do you handle a space in a path in Linux?

The solutions are to use quotes or the backslash escape character. The escape character is more convenient for single spaces, and quotes are better when there are multiple spaces in a path. You should not mix escaping and quotes.


2 Answers

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

mkdir -pv "$outputdir"
like image 59
Jonathan Leffler Avatar answered Oct 16 '22 12:10

Jonathan Leffler


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"
like image 44
jordanm Avatar answered Oct 16 '22 12:10

jordanm