If I do cd "user/Dropbox/foo.txt", I get -bash: cd: user/Dropbox/foo.txt: Not a directory. But my intention in this case is always the same: I want to cd to the directory the file is in.

I tried this:

function smartcd
    dirname=$(dirname "$1");
    cd $dirname;

But it doesn't work because when $1 is a directory, dirname "$1" returns the parent directory, not the directory itself.

How can I create a command that will cd to the directory itself if $1 is a directory, or to the directory the file is in if $1 is a file?

  • 1
    Doesn't zsh do this already? If not, maybe it should...? – 0xSheepdog Apr 21 '17 at 21:26

I think what you want is to test $1 for a file first:

if test -f "$1"; then cd dirname ... else cd "$1" fi

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