2

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!

1
  • Note that it is unlikely that you need to export that variable. Jan 21, 2011 at 18:01

4 Answers 4

10

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

1
  • I tried the following: export my_dir="\"my dir\"" ... notice the double-doublequotmark escaping... now echo $my_dir echoes "my dir"... but still cd $my_dir returns -bash: cd: "my: No such file or directory ... I don't get it
    – Abdull
    Feb 4, 2013 at 13:54
1

Doing

cd "$my_dir"

works, but then you'll always have to remember that for my_dir you'll need to use "my_dir". An alternative solution is that you can do:

ln -s my\ dir my_dir
export my_dir="my_dir"

And now you should be able to do:

cd $my_dir

So basically create a Symbolic Link to the directory with the space and then export the symlink instead of the actual directory.

0
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.

2
  • Thanks for tip! the alias can work, but i prefer using a variable. I think bdonlan's way is great.
    – user59285
    Jan 21, 2011 at 14:47
  • You can also do alias cdmydir='cd "my dir"'. Jan 21, 2011 at 18:03
0

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.

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .