Programming
bash shell csh tcsh
Updated Fri, 20 May 2022 07:15:12 GMT

Can a shell script set environment variables of the calling shell?


I'm trying to write a shell script that, when run, will set some environment variables that will stay set in the caller's shell.

setenv FOO foo

in csh/tcsh, or

export FOO=foo

in sh/bash only set it during the script's execution.

I already know that

source myscript

will run the commands of the script rather than launching a new shell, and that can result in setting the "caller's" environment.

But here's the rub:

I want this script to be callable from either bash or csh. In other words, I want users of either shell to be able to run my script and have their shell's environment changed. So 'source' won't work for me, since a user running csh can't source a bash script, and a user running bash can't source a csh script.

Is there any reasonable solution that doesn't involve having to write and maintain TWO versions on the script?




Solution

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.





Comments (4)

  • +0 – @KrisRandall Actually the answer is correct!! source script.sh == . script.sh — Jun 02, 2019 at 19:54  
  • +1 – See also: env2, "a unix perl script to convert environment variables between scripting languages." This is specifically linked from the Environment Modules home page under "Related tools" — Sep 03, 2021 at 04:02  
  • +0 – Is it possible to run the Nodejs app through the debugger when instantiating the app this way? This is what I do, but can't seem to get it to run via launch.json: "./path-to-script/script.sh .env npm start" — Dec 30, 2021 at 20:50  
  • +0 – what do you mean, by saying "you may just want to bite the bullet and maintain one for each of the two flavors of shell."? — Feb 24, 2022 at 09:27