问题
I am not able to set env
variables through an executable csh/tcsh
script
An env
variable set inside a csh/tcsh
executable script "myscript"
contents of the script ...
setenv MYVAR /abc/xyz
which is not able to set on the shell and reports "Undefined variable"
I have made the csh/tcsh
script as executable by the following shell command
chmod +x /home/xx/bin/myscript
also the path is updated to
set path = (/home/xx/bin $path)
which myscript
/home/xx/bin/myscript
When I run the script on command line and echo the env variable ..
myscript
echo $MYVAR
MYVAR "Undefined variable"
but if i source on command line
source /home/xx/bin/myscript
echo $MYVAR
/abc/xyz
回答1:
you need to source
your code rather than execute it so that it is evaluated by the current shell where you want to modify the environment.
You can of course embed
source /home/xx/bin/myscript
within your .cshrc
the script does not need to be executable or have any #!
shebang (though they don't hurt)
回答2:
This is not how environment variables work.
An environment variable is set for a process (in this case, tcsh
) which is passed on to all child processes. So when you do:
$ setenv LS_COLORS=foo
$ ls
You first set LS_COLORS
for the tcsh
process, tcsh
then starts the child process ls
which inheres tcsh
's environment (including LS_COLORS
), which it can then use.
However, what you're doing is setting the environment is a child process, and then want to propagate this back to the parent process (somehow). This is not possible. This has nothing to do with tcsh
, it works like this for any process on the system.
It works with source
because source
reads a file, and executes it line-by-line in the current process. So it doesn't start a new tcsh
process.
I will leave it as an exercise to you what the implications would mean if it would be possible :-) Do you really want to deal with unwise shell scripts that set some random environment variables? And what about environment variables set by a php
process, do we want those to go back in the parent httpd
process? :-)
You didn't really describe what goal you're trying to achieve, but in general, you want to do something like:
#!/bin/csh -f
# ... Do stuff ...
echo "Please copy this line to your environment:"
echo "setenv MYVAR $myvar"
来源:https://stackoverflow.com/questions/28738107/csh-script-as-executable-does-not-setenv