Executing cd in a bash function called by subshell causes extraneous output

bashterminal

Consider the bash function:

func() {
  cd /;
  echo test;
}

Calling it does what you'd expect:

~:>func
test
/:>

But when called from a subshell (eg using backticks or $()) it performs very strangely.

~:>func() { cd /; echo test; }
~:>echo $(func)
test Saving session... ...saving history...truncating history files... ...completed.
~:>

This issue does not appear if cd is not executed in the function:

~:>func() { echo test; }
~:>echo $(func)
test
~:>

This is causing issues with some scripts that rely on certain output behavior, eg CLASSPATH=$(func) where func is complex and requires the use of cd.

What's strange is that this worked fine before. It did not start to happen until recently, but I don't know what would have caused it.

Note: alias cd reports "alias: cd: not found" and which cd returns /usr/bin/cd which is a script that is identical to another Mac which does not have the problem.

Best Answer

There seems to be something odd going on as cd is not defined to behave as you are seeing it. Evidence suggests it's definition is being over-ridden somewhere.

It is possible that your cd command is aliased somewhere. The alias command with no arguments will display a list of aliased commands on most shells. A workaround for an aliased command is to preface the command with a backslash (\cd). That quotes the first letter of the command and defeats any alias processing by the shell.

It is also possible that it is a shell function. declare -f should list the defined functions, at least in bash, and you can see if cd is being defined as a function.

With luck, your which command may support short-cut ways to do these checks. Check out this on-line man page for how one implementation of which can be used to check functions and aliases, then see if your which operates in a similar manner.