Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting environment variable in shell script does not make it visible to the shell

I want to use a shell script that I can call to set some environment variables. However, after the execution of the script, I don't see the environment variable using "printenv" in bash.

Here is my script:

#!/bin/bash  echo "Hello!" export MYVAR=boubou echo "After setting MYVAR!" 

When I do "./test.sh", I see:

Hello! After setting MYVAR! 

When I do "printenv MYVAR", I see nothing.

Can you tell me what I'm doing wrong?

like image 475
GDICommander Avatar asked Dec 22 '11 13:12

GDICommander


People also ask

How can I see environment variables in shell?

Under bash shell: To list all the environment variables, use the command " env " (or " printenv "). You could also use " set " to list all the variables, including all local variables.

How do I pass an environment variable in bash script?

The easiest way to set environment variables in Bash is to use the “export” keyword followed by the variable name, an equal sign and the value to be assigned to the environment variable.

Does shell script inherit environment variable?

Environment variables are inherited by child shells but shell variables are not. Shell variable can be made an environment variable by using export command. A script is simply a collection of commands that are intended to run as a group.

How do you display a variable in a shell script?

Using the echo command you can display the output of a variable or line of text. It requires no formatting while implementing this option. The echo command is useful to display the variable's output especially when you know the content of a variable will not cause any issue.


2 Answers

This is how environment variables work. Every process has a copy of the environment. Any changes that the process makes to its copy propagate to the process's children. They do not, however, propagate to the process's parent.

One way to get around this is by using the source command:

source ./test.sh 

or

. ./test.sh 

(the two forms are synonymous).

When you do this, instead of running the script in a sub-shell, bash will execute each command in the script as if it were typed at the prompt.

like image 99
NPE Avatar answered Sep 18 '22 00:09

NPE


Another alternative would be to have the script print the variables you want to set, with echo export VAR=value and do eval "$(./test.sh)" in your main shell. This is the approach used by various programs [e.g. resize, dircolors] that provide environment variables to set.

This only works if the script has no other output (or if any other output appears on stderr, with >&2)

like image 43
Random832 Avatar answered Sep 19 '22 00:09

Random832