cd

Summary

cd ?dirName?

Change the current directory (as returned by pwd) to the given directory. If dirName is omitted, change to the user's home directory (or whatever is listed in the ::env(HOME) variable).

Documentation

man page

Description

cd stands for change directory. This sets a kernel specific piece of information regarding what files within a filesystem the application will see if they use relative pathnames (that is to say, pathnames either beginning with ./ , ../ , or without any leading directory indicatory).

This kernel value is a unique value per process - changing it in one process won't change it in other existing processes.

frequently-made mistake is to attempt to [[exec] the cd command.

AMG: Here's an exception. [[exec]'ing cd is actually correct when the "cd" in question comes from the execline package, in which everything'' is accomplished through Bernstein chaining. See [L1 ] for documentation on this variant of cd.

Stacking cd

The following overloaded version keeps a stack of visited directories (implicit "pushd"). The "popd" functionality fires if called as "cd -":

if {[info command tcl::cd]==""} {rename cd tcl::cd}
proc cd {{dir ""}} {
    global cd_stack
    if {$dir=="-"} {
        set dir [lindex $cd_stack end]
        set cd_stack [lrange $cd_stack 0 end-1]
    } else {
       if {$dir==""} {set dir $::env(HOME)}
       lappend cd_stack [pwd]
    }
    tcl::cd $dir
} ;# RS

A variant with a little more error checking, an no reliance on env(HOME):

if {[llength [info command tcl::cd]] == 0} { rename cd tcl::cd }
proc cd {{dir {}}} {
    variable tcl::cd_lastdir
    set pwd [pwd]
    if {$dir eq "-"} {
        if {![info exists cd_lastdir]} { return }
        set dir $cd_lastdir
    } elseif {[llength [info level 0]] == 1} {
        # no $dir specified - go home
        set code [catch {tcl::cd } res]
    }
    if {![info exists code]} {
        set code [catch {tcl::cd $dir} res]
    }
    if {!$code} { set cd_lastdir $pwd }
    return -code $code $res
}; # JH

MCR However, the tcl::cd command does not change the Windows Drive letter. To do that XXX.

AM You mean, you expect it to behave as:

% pwd
c:/tcl
% cd d:
% pwd
d:/
% cd c:
c:/tcl

So, changing the drive would get you back to the previous directory on that drive?

The ordinary cd command does not do that - "cd c:" is treated as "cd c:/". (Personally I find it a trifle annoying to have to run two commands in a DOS-box to go to a different directory on a different drive ...)

RS: Oh, with an extra "/d" option you can in cmd.exe:

H:\>cd /d d:/Tcl

D:\Tcl>

With a bit of work you can have the behaviour you want though :).