6

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?

1 Answer 1

8

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).

2
  • Is it possible for the function to add a -v/--verbose flag to cd?
    – leetbacoon
    Commented Dec 14, 2019 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 Commented Dec 14, 2019 at 16:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .