2

I'm realtivly new to bash as having always developed on a windows machine (yeah i know). Until recently I have been able to cd into a dir by using

cd a\ dir\ name\ with\ spaces/

but suddenly this does not work any longer. Even using TAB auto-complete it will generate the proper escapes but I'm always met with something like

-bash: cd: a: No such file or directory

a friend mentioned it may be path related. Can anyone shed some light on this issue for me?


Below is my .bash_profile

# Exe subshell script
source ~/.bashrc

And the .bashrc

function cs ()
{
  cd $1
  ls
}

# A new version of "cd" which
# prints the directory after cd'ing
cd() {
        builtin cd $1
        pwd
}
3
  • it will generate the correct command meaning it will generate the escapes properly? I can't imagine it "suddenly" doesn't work. Have you altered any of bash's personal configuration files (e.g. ~/.bash_profile)?
    – slhck
    Commented Mar 15, 2012 at 13:18
  • have edited. Yes I did edit bash_profile. I just had a look and commented out my last edit 'source ~/.bashrc' and it works again! This was to add an extra function 'cs' that is contained in .bash_rc using a similar approach described joshstaiger.org/archives/2005/07/bash_profile_vs.html for osX. Any idea why this stops escaping spaces working?
    – Dori
    Commented Mar 15, 2012 at 13:29
  • done, have added to OP
    – Dori
    Commented Mar 15, 2012 at 13:44

1 Answer 1

5

A correct replacement would be:

cd() {
    builtin cd "$1"
    pwd
}

You need to quote a variable that contains spaces when it's expanded if you want to retain them.


Why do I need to do this?

Let's examine:

  • Let's say you call your custom cd function with the argument with\ spaces.
  • Obviously, you need to do this, since otherwise, your function would get two arguments, namely with and spaces.
  • So, correctly escaping, your function gets with spaces as one argument.
  • You pass this argument to builtin cd using $1.
  • $1 is automatically expanded to with spaces (since that's what the function received).
  • Your call now is builtin cd with spaces/
  • That again results in a call to cd with the two arguments with and spaces.

So to fix it:

  • Quote $1 with double quotes.
  • The command is expanded to builtin cd "with spaces".
  • Now cd is correctly called with one argument again.

Another possibility is to just use a more generic "$@" instead of "$1" to pass all parameters and not only the first one to another script. This is what you want to do in 99% of all cases.

cd() {
    builtin cd "$@"
    pwd
}

Obviously, the same fix applies to your cs() function.

1
  • 1
    +1 Also need to quote the "$1" in the cs function. Commented Mar 15, 2012 at 13:52

You must log in to answer this question.

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