How to cd to a directory that contains a space in its name?

47

5

I have a directory called "Reader 0.5" in my Desktop on Mac Os X. When to access the directory in terminal, I am using below code:

cd /Users/niho/Desktop/Reader 0.5

but it throws:

No such file or directory

error.

How can I cd into that directory?

Thanks.

Valentina

Posted 2011-03-13T11:06:35.537

Reputation:

Answers

65

Either you put quotes around the directory name (cd "/Users/niho/Desktop/Reader 0.5") or you escape the directory name (/Users/niho/Desktop/Reader\ 0.5).

joschi

Posted 2011-03-13T11:06:35.537

Reputation: 981

Now: how do you place the path with the infix spaces into an env var so you can do % cd $foo ? – Bogatyr – 2015-10-08T22:42:16.853

6Just for the sake of completeness, you can also decide to quote just parts of the argument, like cd /Users/niho/Desktop/"Reader 0.5" or even cd /Users/niho/Desktop/Reader" "0.5 – user123444555621 – 2011-03-13T12:14:59.043

3The last one (infix quotes) was new to me. Thank you! – joschi – 2011-03-13T17:07:42.793

8

You can escape the space:

cd /Users/niho/Desktop/Reader\ 0.5

Felix

Posted 2011-03-13T11:06:35.537

Reputation: 4 095

4

As others have mentioned, quoting the path or backslash-escaping the spaces will work.

In addition bash, the default shell on Mac OS X, supports command-line completion using the Tab key. So e.g. if you type:

cd /Users/niho/Desktop/Re

then press the Tab key, the shell will fill in the rest of the folder name (as long as there are no other folders on your Desktop starting with "Re"), and will take care of quoting the arguments to cd if there are spaces in the directory name it fills in.

Simon Whitaker

Posted 2011-03-13T11:06:35.537

Reputation: 206

4

Fyi, using the Tab in bash shortcut would break at the first space it encounters if multiple directories have identical first names. In such cases a user would have to use:

cd Adobe\ Creative\ Cloud/

or what I prefer,

cd 'Adobe Creative Cloud'

Ricardo Fernandez

Posted 2011-03-13T11:06:35.537

Reputation: 41

On both bash and zsh, the quoting does not work for me :


2 => cd '~/Library/'
bash: cd: ~/Library/: No such file or directory
3 => cd ~/Library/
4 => pwd
/Users/pguruprasad/Library
 – Prasanth  – 2016-05-31T22:08:53.137

-1

Here's a more comfortable way if you want use the cd commands to certain directories more often. It avoids writing the directory name every time.

In your .bashrc or .profile, insert:

# activate cdable_vars
shopt -s cdable_vars

# define shortcut for your directory, here DIR
export DIR="/Users/<username>/path/to/your/dir"

Execute your script once: . .bashrc

Then you can cd to your directory like this:

cd DIR

This should work even if the path contains spaces.

In shell scripting, however, you must quote the variable like this:

cd "$DIR"

Agile Bean

Posted 2011-03-13T11:06:35.537

Reputation: 129