csh commands within csh scripts
Jonathan I. Kamens
jik at athena.mit.edu
Sat Nov 3 04:18:54 AEST 1990
At the end of this message is included the answer to question number 14 in
the monthly comp.unix.questions Frequently Asked Questions posting. It
doesn't mention aliases specifically, but the logic behind aliases is exactly
the same as the logic behind environment variables, described below.
If you've already read the FAQ posting, but didn't make the connection
between aliases and subshells, then now you know. If you haven't bothered to
read the FAQ posting, shame on you. Check comp.unix.questions at your site
for the most recent version (it should be posted again in a day or two, if it's
expired), or E-mail me and I'll send you a copy.
--
Jonathan Kamens USnail:
MIT Project Athena 11 Ashford Terrace
jik at Athena.MIT.EDU Allston, MA 02134
Office: 617-253-8085 Home: 617-782-0710
------------------------------------------------------------------
14) How do I {set an environment variable, change directory} inside a
shell script and have that change affect my current shell?
You can't, unless you use a special command to run the script in
the context of the current shell rather than in a child program.
The process environment (including environment variables and
current directory) is inherited by child programs but cannot be
passed back to parent programs.
For instance, if you have a C shell script named "myscript":
cd /very/long/path
setenv PATH /something:/something-else
or the equivalent Bourne or Korn shell script
cd /very/long/path
PATH=/something:/something-else export PATH
and try to run "myscript" from your shell, your shell will fork and run
the shell script in a subprocess. The subprocess is also
running the shell; when it sees the "cd" command it changes
*its* current directory, and when it sees the "setenv" command
it changes *its* environment, but neither has any effect on the current
directory of the shell at which you're typing (your login shell,
let's say).
In order to get your login shell to execute the script (without forking)
you have to use the "." command (for the Bourne or Korn shells)
or the "source" command (for the C shell). I.e. you type
. myscript
to the Bourne or Korn shells, or
source myscript
to the C shell.
If all you are trying to do is change directory or set an
environment variable, it will probably be simpler to use a
C shell alias or Bourne/Korn shell function. See the "how do
I get the current directory into my prompt" section
of this article for some examples.
More information about the Comp.unix.shell
mailing list