bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: "Partial Path" cd


From: Mark Johnson
Subject: Re: "Partial Path" cd
Date: 23 May 2001 21:58:06 GMT

In article <010523210424.AA99006.SM@nike.ins.cwru.edu>,
Chet Ramey <chet@po.CWRU.Edu> wrote:
>> I tend to do this a lot after editing a file (vi .../README) and then 
>> want to change to the directory that had that file in it, so I type
>> cd ESC-. RET so bash tries to cd /usr/local/README.
>
>Post the shell function.  Mine took eleven lines and two minutes (without
>any option parsing).
>
[...]

Well I added mine to an existing cd function that emulates the ksh
2 argument cd functionality (Originally by Chet I believe).

This version handles /usr/local/nopermdir, dumping the user in /usr/local.
Other then that the eleven liner is more elegant - my shell scripting 
could be summed up as:  "Bang two rocks together - I make fire!" :-)

The C patch I have works along the same line, except it builds up the
new path by checking that each component is a directory and that 
EACCESS(path, X_OK) == 0 then returning newpath to cd_builtin().

cd()
{
    OPTIND=1
    while getopts "LP" opt
    do
        case $opt in
        L|P)    CDOPTS="$CDOPTS -$opt" ;;
        *)      echo "$FUNCNAME: usage: $FUNCNAME [-LP] [dir] [change]" >&2
                return 2;;
        esac
    done

    shift $(( $OPTIND - 1 ))

    case $# in
    0)      builtin cd $CDOPTS "$HOME" ;;
    1)      builtin cd $CDOPTS "$@" && return

            SAVEPWD="$PWD"
            OLDIFS="$IFS"       
            IFS=/
            for e in $@
            do
                if [[ $e == "" ]]
                then
                    builtin cd /
                else
                    builtin cd $e || break
                fi
            done
            IFS="$OLDIFS"
            OLDPWD="$SAVEPWD"
            echo "$PWD"
            ;;
     2)     old="$1" new="$2"
            case "$PWD" in
            *$old*) ;;
            *)   echo "${0##*/}: $FUNCNAME: bad substitution" >&2 ; return 1 ;;
            esac

            dir=${PWD//$old/$new}

            builtin cd $CDOPTS "$dir" && echo "$PWD"

            ;;
    *)      echo "${0##*/}: $FUNCNAME: usage: $FUNCNAME [-LP] [dir] [change]" 
>&2
            return 2 ;;
    esac
} 


-- 
Mark Johnson
mjohnson@enteract.com



reply via email to

[Prev in Thread] Current Thread [Next in Thread]