Skip to content

cd ~- fails if $OLDPWD is undefined #1457

Open
@krader1961

Description

@krader1961

While removing problematic uses of getconf LIBPATH I noticed the src/cmd/ksh93/tests/exit.sh unit test contains these lines that I added almost two years ago to get the cd ~- test at the end of that unit test to pass:

# This would be gratuitous since our CWD should be $TEST_DIR but the `cd ~-` below requires we do
# this for it to succeed.
cd $TEST_DIR || { err_exit "cd $TEST_DIR failed"; exit 1; }

That workaround is needed on every platform other than macOS. This includes both the current version of ksh and ksh93u+. Which includes OpenIndiana (a Solaris clone), FreeBSD, OpenBSD, and several flavors of Linux. All you have to do is start a new shell and type cd ~-. On every platform other than macOS you get an error such as this (from ksh93u+ on OpenIndiana):

/bin/ksh: cd: ~-: [No such file or directory]

This is because OLDPWD is not defined by a new shell on most platforms. For example, on OpenIndiana:

$ /bin/ksh
KSH PROMPT:1: echo $OLDPWD

KSH PROMPT:2:

On MacOS:

$ /bin/ksh
KSH PROMPT:1: echo $OLDPWD
/Users/krader
KSH PROMPT:2:

Note that this behavior is true for both the last stable, ksh93u+, release and the current git master branch. This "just works" on macOS, but no other platform I have access to, because on macOS OLDPWD (at least for my shell environment) is exported and thus is imported by a new ksh instance. Presumably the old test framework implicitly did a cd in the context of the unit test prior to executing the body of the unit test. Thus making the final cd ~- "valid".

Explain to me why these two commands produce different failure modes on every system I have access to other than macOS (where OLDPWD is exported):

$ cd -
/bin/ksh: cd: no OLDPWD
$ cd ~-
/bin/ksh: cd: ~-: bad directory

It seems to me that cd ~- should be no-op if no prior cd has been executed.

P.S., bash also exhibits the same behavior. If OLDPWD is in the environment when a bash shells starts it is usable by cd ~-. If not you get a failure. And a google search suggests this is, more or less, expected behavior that is undefined by the POSIX shell specification. "More or less" because there seems to be some ambiguity regarding the "correct" behavior.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions