~ won't expand to user folder

If you’ve used bash before, then the tilde (~) is probably familiar to you. It’s a shortcut for your home folder in the terminal. Thus, cd ~ on my system works as follows:

1
2
3
4
5
6
$ cd / $ pwd / $ cd ~ $ pwd /Users/erichu

This is great, but I’ve run into hiccups using this in scripts or certain situations.

1
2
3
4
5
6
7
8
9
10
11
$ mkdir 'folder with spaces' $ cd folder\ with\ spaces/ $ pwd /Users/erichu/folder with spaces # This works $ cd ~/folder\ with\ spaces/ # This doesn't $ cd "~/folder\ with\ spaces/" -bash: cd: ~/folder\ with\ spaces/: No such file or directory

Tilde doesn’t expand to home when quoted, either with single or double quotes. A workaround is to expand the home folder manually:

1
2
3
4
5
6
7
$ cd "$HOME/folder with spaces" $ pwd /Users/erichu/folder with spaces # NOTE: bash variables don't expand within single quotes $ cd '$HOME/folder with spaces' -bash: cd: $HOME/folder with spaces: No such file or directory