Score:0

How to escape whitespace in variable passed to cd

be flag

I am using WSL on windows 10 with Ubuntu.
The path to a directory I use frequently includes a directory with a space in the name. I can't change that name. The path to the directory is very long:
/mnt/c/Users/name/Dropbox/My PC (Laptop...)/Desktop/Studies/Python
So I would like to create a variable in .bashrc by the name of $PROJECTPATH that would be equal to the directory's path.
That way I could call or alias cd $PROJECTPATH and get to my files.
I tried writing:

PROJECTPATH='/mnt/c/Users/name/Dropbox/My\ PC\ \(Laptop...\)/Desktop/Studies/Python'

alias prjct='cd $PROJECTPATH'

but when running prjct I'd get the error message "too many arguments" which means there's a space being passed to cd.
How could I escape whitespaces when passing a variable to cd or any other command?
And should I export this kind of variable?

cn flag
This effect is called [word splitting](https://www.gnu.org/software/bash/manual/bash.html#Word-Splitting). See [this entry in the bash-hackers.org wiki](https://wiki.bash-hackers.org/syntax/words#word_splitting)
ARunningFridge avatar
be flag
@glennjackman Worked perfectly :). Many thanks!
bac0n avatar
cn flag
`alias a='builtin cd "$b";:'` you can terminate your alias with `:` or `true` this will suppress any additional arguments.
Score:2
my flag

You need to put double quotes around $PROJECTPATH in your alias definition.

Also, I recommend against backslashes in your variable definition. It's less readable and isn't needed in this case:

PROJECTPATH='/mnt/c/Users/name/Dropbox/My PC (Laptop...)/Desktop/Studies/Python'

alias prjct='cd "$PROJECTPATH"'
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.