Search code examples
bashaliascd

Customize "cd" in bash


I just think that it is convenient for me to "cd" to the directory where I store some file, ie.

[admin@local /]$ cd /usr/bin/somefile.pl

which as far as I know that the official "cd" command will not work.

so I wrote something like this:

main () {
    if [[ "${1}" =~ "(.+/)*(.*){1}" ]] && [ -f "${1}" ] ; then
            `\cd ${1%/*}`
    elif [ -f "${1}" ] ; then
            exit 0
    else ; `\cd ${1}`
    fi
}
main ${1}

and I alias this cd.sh to the "cd" command:

alias cd='source /somepath/cd.sh'

and this doesn't work.

I've tried to use eval "\cd xxx" instead of just \cd xxx;

How can I fix my script?


Solution

  • It feels like a bad idea to override cd, so I'll suggest a slightly different command, fcd:

    fcd() { cd -- "$(dirname -- "$1")"; }
    
    $ fcd /usr/bin/somefile.pl
    $ pwd
    /usr/bin
    

    Or using parameter expansion to save a call to dirname:

    fcd { cd -- "${1%/*}"; }