Gary
Gary

Reputation: 4241

cd to a path variable in .bash_profile with spaces, without using quotes

In my .bash_profile, I've got: dl="/Users/gary/Downloads. When I go to Terminal and type cd $dl, it goes to the dir, as expected.

But when I have the following line in .bash_profile:

applib="/Users/gary/Library/Application Support"

And I type cd $applib then it doesn't work, due to the space in the path.

I know that cd "$applib" does work, though, but is there a way to make it so that I don't need the quotes? Otherwise, I'd have to remember which of my path variables need the quotes and which don't, for instance.

Upvotes: 1

Views: 1864

Answers (2)

choroba
choroba

Reputation: 241968

Variables are expanded before word splitting. There's no other way how to keep the spaces than quoting. See man bash:

The order of expansions is: brace expansion, tilde expansion, parameter, variable and arithmetic expansion and command substitution (done in a left-to-right fashion), word splitting, and pathname expansion.

Instead of remembering when to use the quotes, use them always. They don't harm the values with no spaces.

Upvotes: 4

Keith Thompson
Keith Thompson

Reputation: 263467

Use the quotes; that's what they're for. You don't need to remember which paths need quotes and which don't; just use them consistently:

cd "$dl"

cd "$applib"

Upvotes: 3

Related Questions