Search code examples
bashshellcd

Is it possible to CD into a file?


I find a list of files that I need to cd to (obviously to the parent directory).

If I do cd ./src/components/10-atoms/fieldset/package.json I get the error cd: not a directory:, which makes sense.

But isn't there a way to allow for that? Because manipulating the path-string is pretty cumbersome and to me that would make total sense to have an option for that, since cd is a directory function and it would be cool that if the path would not end up in a file, it would recursively jump higher and find the "first dir" from the given path.

So cd ./src/components/10-atoms/fieldset/package.json would put me into ./src/components/10-atoms/fieldset/ without going on my nerves, telling me that I have chosen a file rather than a dir.


Solution

  • This function should do what you need:

    cdd() { test -d "$1" && cd "$1" || cd $(dirname "$1") ; }
    

    If its first argument "$1" is a directory, just cd into it, otherwise cd into the directory containing it.

    This function should be improved to take into account special files such as devices or symbolic links.