Restrictions preventing /usr/bin/cd from accessing $OLDPWD

It is worth noting that command names are usually written in lowercase letters, whereas shell environment variables are typically written in uppercase letters. If you want to view the values of the variables mentioned, you can use a command similar to the following. To output array variables, you can use the syntax “${ARR_NAME[$index]}.

Question:

Encountered an intriguing issue that remains uncertain to me. Upon utilizing bash’s internal cd, I successfully execute

cd -

. However, when utilizing the cd executable, an error arises with the message:

/usr/bin/cd: line 2: cd: OLDPWD not set

.

Here’s a transcript:

$ cd /tmp
$ cd $HOME
$ echo $OLDPWD 
/tmp 
$ /usr/bin/cd - 
/usr/bin/cd: line 2: cd: OLDPWD not set 
$ declare -xp OLDPWD 
declare -x OLDPWD="/tmp"



Solution 1:

The origin of the

cd

executable is uncertain, but it serves no purpose. Its functionality is limited to changing its own working directory and not that of the shell. Therefore,

cd

must be a builtin and can only operate in that way.


Solution 2:


Discovered the solution in

#bash

while on irc.freenode.net.

It appears that the

/usr/bin/cd

file you are trying to execute is not a genuine binary.

$ cat /usr/bin/cd
#!/bin/sh
builtin cd "$@"

Whenever

sh

is started, it runs /usr/bin/cd in a subshell executing

sh

. As a result, the child shell disregards/unsets the variables

PWD

and

OLDPWD

set by the parent shell, which is why

$OLDPWD

appears to be untraceable.

Frequently Asked Questions