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?

Answers


Each and every shell has its own environment. There's no Universal environment that will magically appear in all console windows. An environment variable created in one shell cannot be accessed in another shell.

It's even more restrictive. If one shell spawns a subshell, that subshell has access to the parent's environment variables, but if that subshell creates an environment variable, it's not accessible in the parent shell.

If all of your shells need access to the same set of variables, you can create a startup file that will set them for you. This is done in BASH via the $HOME/.bash_profile and $HOME/.bashrc files and through $HOME/.profile if $HOME/.bash_profile doesn't exist). Other shells have their own set of startup files. One is used for logins, and one is used for shells spawned without logins. See the manpage to learn exactly what startup scripts are used and what order they're executed).

You can try using shared memory, but I believe that only works while processes are running, so even if you figured out a way to set a piece of shared memory, it would go away as soon as that command is finished. (I've rarely used shared memory except for named pipes). Otherwise, there's really no way to set an environment variable in one shell and have another shell automatically pick it up. You can try using named pipes or writing that environment variable to a file for other shells to pick it up.

Imagine the problems that could happen if someone could change the environment of one shell without my knowledge.


Just run your shell script preceded by ". " (dot space). It does the shell be executed in the same shell you are.

This causes the shell to run the same original shell. Thus the variables still exist after the shell finish

Ex:

cat setmyvar.sh
export myvar=exists

. ./setmyvar.sh

echo $myvar
exists

Need Your Help

How to change author name on git branch

git branching-and-merging amend

I branched my github project to create the static page the other day but messed up with my author name

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.