Cameron Laird's personal notes on changing directories

Developers and administrators often ask how to change directory programmatically, that is, "cd" to the result of a computation. This is my answer.

You can't.

Well, you can, but not the way you think you want.

This is an FAQ with a loooong history; I know it was a common confusion at the end of the '70s, and I have strong memories of authoritative explanations published in the '80s. As I haven't been able quickly to track down any such explanations, I decided to sketch my own. I'd welcome tips to better ones.

Conventional contemporary operating systems feature "file systems"--hierarchies of directories and files--prominently. It's natural, and nearly as ubiquitous as the filesystems themselves, to reify the notion of "present directory" or "current working directory".

This leads, fairly quickly and almost equally as naturally, to questions like this: "I have a script,

    first_command
    my_command
    second_command
  
and I need my_command to change the directory of its parent. How can I do that?"

You can't.

My concrete examples are Unix ones; they generalize easily. Under Unix (POSIX?), security considerations severely limit the scope of a child's actions. In particular, children can't change their parents' working directories (under shell and its descendants).

However, it is possible to answer a slightly different question affirmatively. If the parent script is modified to

     first_command
     eval `my_command`
     second_command
   
and my_command writes a string such as "cd /a/special/directory", then ... [four alternatives; ...]

[Important: Wiki page on "Setting /bin/sh environment variables in the script".]

[Explain how the answer for Windows is roughly the same.]


Cameron Laird's personal notes on changing directories/claird@phaseit.net