What's the best practice for changing working directories inside scripts?

bash, perl, shell, zsh

Solution

The current working directory is local to the executing shell, so you can't affect the user unless he is "dotting" (running it in the current shell, as opposed to running it normally creating a new shell process) your script.

A very good way of doing this is to use subshells, which i often do in aliases.

alias build-product1='(cd $working-copy/delivery; mvn package;)'

The paranthesis will make sure that the command is executed from a sub-shell, and thus will not affect the working directory of my shell. Also it will not affect the last-working-directory, so cd -; works as expected.

Problem

Do you think changing directories inside bash or Perl scripts is acceptable? Or should one avoid doing this at all costs? What is the best practice for this issue?

Original source