Can a shell script set environment variables of the calling shell? [duplicate] Can a shell script set environment variables of the calling shell? [duplicate] bash bash

Can a shell script set environment variables of the calling shell? [duplicate]


Use the "dot space script" calling syntax. For example, here's how to do it using the full path to a script:

. /path/to/set_env_vars.sh

And here's how to do it if you're in the same directory as the script:

. set_env_vars.sh

These execute the script under the current shell instead of loading another one (which is what would happen if you did ./set_env_vars.sh). Because it runs in the same shell, the environmental variables you set will be available when it exits.

This is the same thing as calling source set_env_vars.sh, but it's shorter to type and might work in some places where source doesn't.


Your shell process has a copy of the parent's environment and no access to the parent process's environment whatsoever. When your shell process terminates any changes you've made to its environment are lost. Sourcing a script file is the most commonly used method for configuring a shell environment, you may just want to bite the bullet and maintain one for each of the two flavors of shell.


You're not going to be able to modify the caller's shell because it's in a different process context. When child processes inherit your shell's variables, they'reinheriting copies themselves.

One thing you can do is to write a script that emits the correct commands for tcshor sh based how it's invoked. If you're script is "setit" then do:

ln -s setit setit-sh

and

ln -s setit setit-csh

Now either directly or in an alias, you do this from sh

eval `setit-sh`

or this from csh

eval `setit-csh`

setit uses $0 to determine its output style.

This is reminescent of how people use to get the TERM environment variable set.

The advantage here is that setit is just written in whichever shell you like as in:

#!/bin/basharg0=$0arg0=${arg0##*/}for nv in \   NAME1=VALUE1 \   NAME2=VALUE2do   if [ x$arg0 = xsetit-sh ]; then      echo 'export '$nv' ;'   elif [ x$arg0 = xsetit-csh ]; then      echo 'setenv '${nv%%=*}' '${nv##*=}' ;'   fidone

with the symbolic links given above, and the eval of the backquoted expression, this has the desired result.

To simplify invocation for csh, tcsh, or similar shells:

alias dosetit 'eval `setit-csh`'

or for sh, bash, and the like:

alias dosetit='eval `setit-sh`'

One nice thing about this is that you only have to maintain the list in one place.In theory you could even stick the list in a file and put cat nvpairfilename between "in" and "do".

This is pretty much how login shell terminal settings used to be done: a script would output statments to be executed in the login shell. An alias would generally be used to make invocation simple, as in "tset vt100". As mentioned in another answer, there is also similar functionality in the INN UseNet news server.