Search code examples
vimcdbash

Bash function to cd and open in vim a filename


When I want to edit a file in vim, I often want to cd to the containing dir before I open the file. My normal process for doing this is...

cd filepath/that/contains/
vim filename.d

But all too often, I end up typing...

cd filepath/that/contains/filename.d
{error: not a directory}

I'd like to create a function that will replace cd. Below is what I came up with, but it doesn't work.

alias cd='vimcd'

function vimcd () {
    if [ -f $1 ]
         then
            cd $(dirname $1) 
            vim $(basename $1)
    else cd $1
    fi
}

Solution

  • I know that this is an old question, but you could just use the vim plugin: NerdTree. This way, you leave cd alone, at the cost of enhancing your editor.

    Your command would just be: $ vim filepath/that/contains

    If it's a file, then it opens it for editing. If it's a directory, then it opens a directory browser.