Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a bash script to set global environment variable?

Recently I wrote a script which sets an environment variable, take a look:

#!/bin/bash  echo "Pass a path:" read path echo $path  defaultPath=/home/$(whoami)/Desktop  if [ -n "$path" ]; then     export my_var=$path else     echo "Path is empty! Exporting default path ..."     export my_var=$defaultPath fi  echo "Exported path: $my_var" 

It works just great but the problem is that my_var is available just locally, I mean in console window where I ran the script.

How to write a script which allow me to export global environment variable which can be seen everywhere?

like image 947
Katie Avatar asked Sep 10 '12 12:09

Katie


People also ask

How do you set an environment variable globally?

Search and select System (Control Panel). Click on the Advanced system settings link and then click Environment Variables. Under the section System Variables, select the environment variable you want to edit, and click Edit. If the environment variable you want doesn't exist, click New.

How do I set environment variables in Git bash?

You must add and edit the “. bashrc” file in the home directory to export or change the environment variable. Then, to make the changes take effect, source the file.


1 Answers

Just run your shell script preceded by "." (dot space).

This causes the script to run the instructions in the original shell. Thus the variables still exist after the script finish

Ex:

cat setmyvar.sh export myvar=exists  . ./setmyvar.sh  echo $myvar exists 
like image 97
JDembinski Avatar answered Sep 18 '22 18:09

JDembinski