I am logging every action performed in a bash script to a logfile. I would like to have cd verbosely change directories so I can record the output to the log.

Kind of like this:

iMac:~ leetbacoon$ cd -v /new\ path
cd: /Users/leetbacoon -> /new path
iMac:new path leetbacoon$

Sadly cd lacks a verbose flag. Any idea on how to get something like this to work?


You may find the shell $OLDPWD shell variable useful (defined by POSIX). For example, you could define a shell function overriding the original cd command:

cd() { command cd "$@" && printf '%s -> %s\n' "${OLDPWD}" "${PWD}"; }

Excerpt from the Unix man page you should read:

If, during the execution of the above steps, the PWD environment variable is set, the OLDPWD environment variable shall also be set to the value of the old working directory (that is the current working directory immediately prior to the call to cd).

  • Is it possible for the function to add a -v/--verbose flag to cd? – leetbacoon Dec 14 '19 at 12:04
  • @leetbacoon it is almost certainly possible - it would take some careful parsing (beyond my abilities) to separate out the -v and pass any remaining parameters to the underlying cd builtin – steeldriver Dec 14 '19 at 16:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.