If having a directory name as "my dir". I can get to the directory use this,

~: cd my\ dir

or

~: cd "dy dir" 

But I found if I do this:

~: export my_dir=my\ dir

or

~: export my_dir="my dir"

then

~: cd $my_dir

it does not work, cd always get its parameter as "my " and report error.

Anyone aware how to fix this?

Thanks!

link|improve this question
Note that it is unlikely that you need to export that variable. – Dennis Williamson Jan 21 '11 at 18:01
feedback

migrated from stackoverflow.com Jan 21 '11 at 14:05

This question came from our site for professional and enthusiast programmers.

3 Answers

up vote 7 down vote accepted

The shell will split variables up on whitespace when used outside of quotation marks. Do cd "$my_dir" instead.

link|improve this answer
that does work. Thanks! – user59285 Jan 21 '11 at 14:35
feedback
alias cdmydir="cd my\ dir"

You won't be able to use this for any other function, like specifying paths, but it'll work for this immediate use.

I tried export my_dir=my\\\ dir and export my_dir="\"my dir\"", so that the environment variable would be my\ dir and "my dir", respectively. But bash must do different parsing for environment variables compared to the regular command line: I got errors "No such file or directory" errors for my\ and "my.

link|improve this answer
Thanks for tip! the alias can work, but i prefer using a variable. I think bdonlan's way is great. – user59285 Jan 21 '11 at 14:47
You can also do alias cdmydir='cd "my dir"'. – Dennis Williamson Jan 21 '11 at 18:03
feedback

c () { cd "$1 $2 $3 $4"; }

In whatever bash file you think should be used. Tabbing adds the / escaping the space, so does dragging it from the GUI.

link|improve this answer
1  
Why not c () { cd "$@"; }? – Dennis Williamson Jan 21 '11 at 18:00
@Dennis: Because "$@" will expand to multiple words; essentially a no-op in this case. "$*" would be closer to this answer. – grawity Jan 21 '11 at 19:53
@grawity: You are correct. – Dennis Williamson Jan 21 '11 at 19:57
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.