I have the following script:#!/bin/shmkdir -p /tmp/test/foocd /tmp/testunset CDPATHecho TEST1: Current working directory: ${PWD}echo TEST1: attempting to 'cd foo'cd fooecho TEST1: Current working directory: ${PWD}cd /tmp/testCDPATH=/tmpecho TEST2: Current working directory: ${PWD}echo TEST2: attempting to 'cd foo'cd fooecho TEST2: Current working directory: ${PWD}Which prints out:$ ./cdpath.shTEST1: Current working directory: /tmp/testTEST1: attempting to 'cd foo'TEST1: Current working directory: /tmp/test/fooTEST2: Current working directory: /tmp/testTEST2: attempting to 'cd foo'./cdpath.sh: line 17: cd: foo: No such file or directoryTEST2: Current working directory: /tmp/testHowever, if I run it as /bin/bash cdpath.sh there is no error, and the TEST2 output is identical to TEST1. The error only occurs if I run it with /bin/sh. I haven't found any documentation about bourne and bourne again shells interpreting CDPATH differently:http://tldp.org/LDP/abs/html/internalvariables.html#CDPATHREFhttp://tldp.org/LDP/abs/html/internal.html#CDREF
Is CDPATH behavior broken in bourne shell (/bin/sh)
linux;bash;shell;cd command
After much more googling and source code checking I found out the reason I'm seeing this behavior is that I'm running bash 3.2. In this version of bash, if you were running in posix mode (which happens when you run bash through /bin/sh) and CDPATH is set, then cd won't search the currently directory unless it's explicitly set in CDPATH. This behavior was included to conform to POSIX.2 (IEEE 1003.2-1992). This reflects what their manual specified at the time. However, for bash 4.2 they changed the behavior in posix mode to match the updated POSIX.1-2008 which now specifies that cd should always search the current working directory even if CDPATH doesn't include it. Bash's new manual now no longer includes this as a difference between posix and non-posix mode because it no longer is different.They made the change by disabling the code that raises an error if posix mode is on by surrounding it with an #if 0 block in builtins/cd.def:#if 0      /* changed for bash-4.2 Posix cd description steps 5-6 */      /* POSIX.2 says that if `.' does not appear in $CDPATH, we don't         try the current directory, so we just punt now with an error         message if POSIXLY_CORRECT is non-zero.  The check for cdpath[0]         is so we don't mistakenly treat a CDPATH value of  as not         specifying the current directory. */      if (posixly_correct && cdpath[0])        {          builtin_error (%s: %s, dirname, strerror (ENOENT));          return (EXECUTION_FAILURE);        }#endifI wish the current bash docs noted the fact that older versions of bash had this behavior.