By default emacs tracks the working directory of a shell by inspecting all commands executed. This is bound to fail, if the working directory is changed by other means like a custom script, e.g., changing between a code directory and the corresponding test directory.
This was annoying me for a while till a few days ago, I decided it was too much. I (essentially) followed the emacs wiki and did the following.
I added the following line to my .emacs_bash to make the bash in emacs produce an easy to recognise prompt.
PS1="|PrOmPt|\w|\w \$ "
In my .emacs configuration file, I require the package dirttrack and configure the hooks in the following way to
;; shell -- dirtrack
(require 'dirtrack)
(add-hook 'shell-mode-hook
(lambda ()
(setq dirtrack-list '("^|PrOmPt|\\([^|]*\\)|" 1 nil))
(dirtrack-mode nil)
(add-hook 'comint-preoutput-filter-functions
'dirtrack nil t)
(add-hook 'comint-preoutput-filter-functions
'dirtrack-filter-out-pwd-prompt t t)))
;; Now strip the goofy strings from the prompt before it gets into
;; the shell buffer.
(defun dirtrack-filter-out-pwd-prompt (string)
"dirtrack-mode doesn't remove the PWD match from the prompt. This does."
(if (and (stringp string) (string-match (first dirtrack-list) string))
(replace-match "" t t string 0)
string))