linux - [Solved-5 Solutions] Can a shell script set environment variables of the calling shell ? - ubuntu - red hat - debian - linux server - linux pc
Linux - Problem :
Can a shell script set environment variables of the calling shell ?
Linux - Solution 1:
- Your shell process has a copy of the parent's environment and no access to the parent process's environment whatsever.
- 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 want to bite the bullet and maintain one for each of the two flavors of shell.
Linux - Solution 2:
Use the "dot space script" calling syntax. For example, here's how to do it using the full path to a script:
Here's how to do it if you're in the same directory as the script:
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.
Linux - Solution 3:
When child processes inherit your shell's variables, they're inheriting copies themselves.
One thing you can do is to write a script that emits the correct commands for tcsh or sh based how it's invoked. If you're script is "setit" then do:
and
Now either directly or in an alias, you do this from sh
or this from csh
setit uses $0 to determine its output style.
The advantage here is that setit is just written in whichever shell you like as in:
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:
or for sh, bash, and the like:
Linux - Solution 4:
In .bash_profile :