Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script to cd to directory with spaces in pathname

Tags:

bash

escaping

People also ask

How do you cd to a directory with a name containing spaces in Bash?

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 I open a directory with spaces in Linux?

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. Using backslash can be confusing; it's easy and better to use quotation marks or apostrophes.

How do you handle spaces in Bash?

Filename with Spaces in Bash A simple method will be to rename the file that you are trying to access and remove spaces. Some other methods are using single or double quotations on the file name with spaces or using escape (\) symbol right before the space.


When you double-quote a path, you're stopping the tilde expansion. So there are a few ways to do this:

cd ~/"My Code"
cd ~/'My Code'

The tilde is not quoted here, so tilde expansion will still be run.

cd "$HOME/My Code"

You can expand environment variables inside double-quoted strings; this is basically what the tilde expansion is doing

cd ~/My\ Code

You can also escape special characters (such as space) with a backslash.


I found the solution below on this page:

x="test\ me"  
eval cd $x

A combination of \ in a double-quoted text constant and an eval before cd makes it work like a charm!


After struggling with the same problem, I tried two different solutions that works:

1. Use double quotes ("") with your variables.

Easiest way just double quotes your variables as pointed in previous answer:

cd "$yourPathWithBlankSpace"

2. Make use of eval.

According to this answer Unix command to escape spaces you can strip blank space then make use of eval, like this:

yourPathEscaped=$(printf %q "$yourPathWithBlankSpace")
eval cd $yourPathEscaped

cd ~/My\ Code

seems to work for me... If dropping the quotes but keeping the slash doesn't work, can you post some sample code?


You can use any of:

cd ~/"My Code"
cd ~/M"y Code"
cd ~/My" Code"

You cannot use:

cd ~"/My Code"

The first works because the shell expands ~/ into $HOME/, and then tacks on My Code without the double quotes. The second fails because there isn't a user called '"' (double quote) for ~" to map to.