1

I have had this function I use it very often and it works fine.

Here it is:

cdx () { cd `dirname $1` ; }

However, this does not work with spaces. When I use it like this for example

cdx ~/desktop/folder/file\ file

It returns

usage: dirname path

But what I am passing is, essentially dirname path. So what am I supposed to do to fix this? (It also does the same thing when there are spaces in a folder names)

My first thought was using quotes, like cdX "directory\ whatever" but it did not work either.

DisplayName
  • 11,688
  • [Leaving a command substitution (\...``) or variable unquoted is the split+glob operator](http://unix.stackexchange.com/q/171346). You don't want to do that here. cdx() { cd -- "$(dirname -- "$1")"; }. – Stéphane Chazelas Jan 13 '15 at 21:57

1 Answers1

1

If you simply write $i, spaces will turn your variable content in multiple arguments. If you want to preserve spaces you have to quote things.

For your example you probably want:

cdx () { cd -- "$(dirname -- "$1")" ; }

And remember always quote your variables.

michas
  • 21,510
  • Why always quote variables? You mean i should edit all my function to be "$1" "$2" whatever instead of $1, $2? – DisplayName Jan 13 '15 at 22:01
  • Exactly. Otherwise you will run into problems when facing paths containing spaces. – michas Jan 13 '15 at 22:02
  • Isn't this okay? cdX () { cd "$(dirname "$1")" ; } – DisplayName Jan 13 '15 at 22:05
  • Yes, that is fine. - Unless your directory happens to start with a dash. Then cd thinks you are giving options instead of an actual path. Adding -- will enforce the argument to be interpreted as an actual pathname. – michas Jan 13 '15 at 22:11