Bash script to cd to directory with spaces in pathname Bash script to cd to directory with spaces in pathname bash bash

Bash script to cd to directory with spaces in pathname


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