'cd' does 'pwd' with relative path but not with absolute path - documented?

Chris Green cl at isbd.net
Fri Jul 3 09:53:44 UTC 2020


On Fri, Jul 03, 2020 at 07:19:32PM +1000, Karl Auer wrote:
> On Fri, 2020-07-03 at 10:56 +0200, Volker Wysk wrote:
> > Am Freitag, den 03.07.2020, 09:28 +0100 schrieb Chris Green:
> > > I have only recently noticed that when running bash in a terminal
> > > 'cd' acts differently for relative and absolute paths.
> 
> This probably means that you have CDPATH set. Read what "man bash" has
> to say about cd, and I think you'll find your answer. This is the
> effect:
> 
> kauer at kt1:~/dev/temp$ pwd
> /home/kauer/dev/temp
> kauer at kt1:~/dev/temp$ ls -lad temp
> drwxrwxr-x 9 kauer kauer 4096 Jun  4 10:48 temp
> kauer at kt1:~/dev/temp$ cd temp
> kauer at kt1:~/dev/temp/temp$ cd ..
> kauer at kt1:~/dev/temp$ export CDPATH=.
> kauer at kt1:~/dev/temp$ cd temp
> /home/kauer/dev/temp/temp
> 
Yes, that's it!  I'd just worked my way there by disabling bits of
.bashrc and .profile.

How weird!  I can't really see the logic behind the way it works, I
suppose there is a bit in that, if CDPATH is set, a 'cd' may take you
to somewhere completely unrelated to the 'from' directory.

As you say it is documented the bash man page but I missed it because
it's right at the bottom of the cd section. ... and it's not
immediately easy to understand, especially the bit about "... or if -
is the first argument,...", it took me a while to get that.

Thanks anyway, I now understand better what's going on.

I have implemented my own cd() function which *always* outputs the
path after being run (that's why I needed the 'builtin' command).
It's very simple:-

    function cd ()
    {
        builtin cd $1
        if [ -z "$1" -o "${1:0:1}" = '/' ]; then
            pwd
        fi
    }

(It will of course not work correctly if CDPATH isn't set, but I
always have CDPATH set. Easy enough to add a further test to see if
CDPATH is set)


-- 
Chris Green




More information about the ubuntu-users mailing list