apadana
apadana

Reputation: 14620

linux cd to folder containing the file

Having a file path I would like to go to the directory of the file. A full path is like this:

/Users/user1/Documents/workspace/project/src/file.py

I would like in terminal to go the folder containing this file. In this case it would be:

/Users/user1/Documents/workspace/project/src/

Right now I have to paste the file in terminal, delete the file name and do cd. Like:

cd /Users/user1/Documents/workspace/project/src/

Is there a command/ any way I can skip deleting the file and use a smart command to know it should go to the directory containing this file?

I have to examine daily a lot of files and deleting the filename from path everytime is becoming a very tedious task.

The desired action would be something like this:

>>smart_cd /path/to/file.py
>>pwd
/path/to

Upvotes: 1

Views: 3317

Answers (2)

Alois Pichler
Alois Pichler

Reputation: 1

This is Chen Levy’s Bonus above, but allows options for cd in addition (as cd -P . to resolve links), as well as links to files and folders.

function cd() {
    if [ $# -eq 0 ] ; then               # no arguments specified
        builtin cd
    elif [[ -f "$1" && -L "$1" ]] ; then # file, which is a link
       cd "$(readlink $1)"               # recursive
    elif [ -f $1 ] ; then                # argument is a file
       builtin cd "$(dirname $1)"
    else                                 # argument is not a file
       builtin cd "$@"
    fi
}

Upvotes: 0

Chen Levy
Chen Levy

Reputation: 16338

Assuming your are using Bash: You can put in your ~/.bashrc

function smart_cd() {
    cd "$(dirname $1)"
}

then: (after re-loading your .bashrc)

$ smart_cd /Users/user1/Documents/workspace/project/src/file.py

Bonus: you can also replace your cd command to handle both normal and smart cd:

function cd() {
    if [ $# -eq 0 ] ; then
        # no arguments
        builtin cd
    elif [ -d $1 ] ; then
        # argument is a directory
        builtin cd "$1"
    else
        # argument is not a directory
        builtin cd "$(dirname $1)"
    fi
}

For more information see:

  • Special Parameters in man bash for $#
  • man test for explanation about [ ... -eq ... ] and [ -d ... ]

Upvotes: 4

Related Questions