Bash script to cd to directory with spaces in pathname


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.

9/21/2018 3:50:30 PM

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.

2/26/2009 5:23:12 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow