Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Convert absolute paths to relative paths



On Fri, 19 Apr 2002, Vin Shelton wrote:

> Thanks, Bart!

Christoph von Stuckrad pointed out privately that if you try to use this
to get a relative path to a *file*, rather than to a directory, it will
go into an infinite loop.

Here's a fix for that:

function relative {
    emulate -L zsh
    local up=.. down
    [[ -d $1 ]] || 2=$1:t 1=$1:h
    [[ -d $1 ]] || return 1
    # ! -d $up/$down accounts for symlinks in $PWD
    while [[ ${PWD#$1} == $PWD || ! -d $up/$down ]]
    do
	up=../$up
	if [[ -n $1:t ]]
	then
	    down=$1:t${down:+/$down}
	    1=$1:h
	fi
    done
    print $up/$down${2:+/$2}
}



Messages sorted by: Reverse Date, Date, Thread, Author