How to overwrite environment variables in mac using Shell Script

Viewed 1407

I have a set of environment variables that need to be set on the basis of the arguments specified in the shell script. But the problem is that those variables are already defined in the bash profile FOR EXAMPLE:

bash_profile has a variable called "KARAN": export KARAN=/config/1

Now on running the shell script, this is what it should do: export KARAN=/config/2 (Changed the bash profile's KARAN value to 2)

2 Answers

Your question is not clear. If your script needs to set the env var to a specific value just do so using export VAR=val. What I think you're asking is how to have a script modify the environment of the current shell. And that is impossible without the cooperation of both shells. That is because environment vars are inherited by child processes. But a child process cannot directly modify the environment of its parent process (or some other random process for that matter). To do so the two processes must coordinate the exchange of data. This is typically done by using the source command if the child process is a shell script. Or by having the child process write a series of export statements to stdout and having the parent shell capture and execute those statements. For example, let's say I have a script named set_env that looks like this

#!/bin/sh
echo export KARAN=/config_2
echo export VAR2=val2

The current shell would then do

eval $(set_env)

Note, however, eval is dangerous. I prefer to do this which is slightly safer:

set_env | source /dev/stdin

That, however, only works in shells like ksh and zsh. Due to how bash handles pipelines the source is actually executed in a child shell and therefore the vars won't be set in the current shell.

You can create a new Profile with all the new definitions. and then call the line below on top of your shell script. Similarly, you can create as many profiles as you want and use it.

    source bash_profile_new
Related