Question

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?

Était-ce utile?

La 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%/*}"; }

Autres conseils

cd() {
    DN="$(dirname "$1")"
    if [[ -d "$1" ]]; then
        builtin cd "$1"
    elif [[ -d "$DN" ]]; then
        builtin cd "$DN"
    else
        echo "$* or $DN: No such directories"
        return 1
    fi
    return 0
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top