arguments for a command file (can't cd within shell)

Ian F. Darwin ian at utcs.UUCP
Sun Dec 23 09:52:18 AEST 1984


	[The original posting describes using `cd' inside a shell file]
	I am attempting to pass the argument by --
	cd $1
	Is this the right way of doing it?
	I print the pwd in the command file and it prints the expected one.
	On using the command pwd outside the command file I find that the
	change in the directory has not been made. Why does it do this?

This is a well-known feature of UNIX. You can cd in a shell file
and it won't hurt your main shell. Thus people writing command
files can cd all they want. But it wasn't intentional, it just
worked that way. In fact, the first people to make the same mistake
you made were Thompson and Ritchie, when they were writing the
current version of UNIX process creation(note 1)! This happens
because the shell is a child process of your interactive shell;
in general a child process cannot change the parent process' environment, 
current directory, etc, etc. And it must be so, otherwise you could change
system processes!

If you do want to change your current directory from within a shell file,
try invoking the shell file as
	. shellfilename newdirectory
if using the real (Bourne) shell, or
	source shellfilename newdirectory
in the C shell. But if all you want is to change directory, use the
cd command. As you can see from the description,
the cd command must be built into the shell.

----------------
Note 1 - See the paper "The Evolution of the UNIX Time-Sharing System"
by Dennis Ritchie. This paper has been reprinted in several places
in 1984, including the October 1984 (AT&T)Bell Labs Technical Journal
and the October 1984 Microsystems (the final issue of Microsystems,
November 1984, has a follow-on paper by myself and Geoff Collyer
with further information on the history of UNIX at Bell Labs).
The discussion of chdir is on page 1585 of the reprint in the BLTJ issue.
-- 
Ian Darwin, Toronto
{ihnp4|decvax}!utcs!ian



More information about the Comp.unix mailing list