Wednesday, April 6, 2011

How do I pass this path to a bash function?

I've been having trouble moving to directories with spaces in the name, but it I just figured it was a problem with Cygwin and worked around it.

Then I found that I could create symbolic links to those directories which made me maybe think it wasn't Cygwin. Then I remembered I created an alias for cd that would list the directory contents and saw this:

cdls { cd $1; ls; }
alias cd='cdls'

So the problem is when I try this it fails:

$ cd /cygdrive/c/Program\ Files/
bash: cd: /cygdrive/c/Program: No such file or directory

I can see that the space is causing the path to be split into multiple arguments, but how do I join them together again?

From stackoverflow
  • Quote it:

    cdls { cd "$1"; ls; }
    

    Quoting in bash can get hairy, since there's multiple levels of interpretation, but it's usually just a matter of playing with it a bit.

    S.Lott : +1: Quote ALL paths in all shell scripts all the time. Always.
    womble : Aye. They might be optional to the parser, but not to me!
  • Try:

    cdls() { cd "$1"; ls; }
    
  • Looks like I just needed to explain the problem for the answer to come to me. My solution is:

    cdls () { cd "$*"; ls ; }
    alias cd='cdls'
    

    Simple.

    womble : I wouldn't use $* in that alias; it will cause problems if you have a path with multiple spaces in it. Also, when using $*, you usually want to use "$@" instead, as it's more robust.

0 comments:

Post a Comment