Bash script to cd to directory with spaces in pathname

Rails Newbie picture Rails Newbie · Feb 26, 2009 · Viewed 152.7k times · Source

I'm using Bash on macOS X and I'd like to create a simple executable script file that would change to another directory when it's run. However, the path to that directory has spaces in it. How the heck do you do this? This is what I have...

Name of file: cdcode

File contents:

cd ~/My Code

Now granted, this isn't a long pathname, but my actual pathname is five directories deep and four of those directories have spaces in the path.

BTW, I've tried cd "~/My Code" and cd "~/My\ Code" and neither of these worked.

Answer

derobert picture derobert · Feb 26, 2009

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.