0

I want to modify environment variable by user given value. For example, user will give the variable to be modified and a value to put in the variable.

I tried the command:

set[variable[=val]]

Its working fine but I don't know if its right way to modify or i have to use export command for that purpose?

My code is :

modify_env(){
echo "Environmental variable:"
read var
echo "Environmental value"
read value
set [var[=value]]
}
heemayl
  • 91,753

1 Answers1

0

From help set:

set: Set or unset values of shell options and positional parameters.

So for the values you are entering with set are literally becoming positional parameters (arguments) to set rather than environment variables.

$ set foo=bar 
$ echo "$foo" ##Prints nothing because it is not a variable

$ echo "$1"  ##Prints the first argument of the command "set foo=bar"
foo=bar

Now from help export:

export: Set export attribute for shell variables.

This is what you need to set a variable throughout the environment i.e. this value will be propagated to all child processes too.

$ export foo=bar  ##setting environment variable foo having value "bar"
$ echo "$foo"  ##printing the value of "foo" in current shell
bar
$ bash -c "echo $foo" ##printing the value of "foo" in a subshell
bar

So, in a nutshell you need to use the export builtin while setting any environment variable.

heemayl
  • 91,753