Linux Classes
Share This With a Friend  
LINUX CLASSES - THE BASICS

Linux Environment Variables

How Do I Set and Use Linux Environment Variables?

Environment Variables

Environment variables in the bash shell help you in several ways. Certain built-in variables change the shell in ways that make your life a little easier, and you can define other variables to suit your own purposes. Here are some examples of built-in shell variables: · PS1 defines the shell's command-line prompt.

· HOME defines the home directory for a user.

· PATH defines a list of directories to search through when looking for a command to execute.

To list the current values of all environment variables, issue the command

env

or list a specific variable with the echo command, prefixing the variable n ame with a dollar sign (the second line shows the result of the echo command):

echo $HOME
/home/hermie

You've already learned how to customize your shell prompt with the PS1 variable. The HOME variable is one you shouldn't mess with, because lots of programs count on it to create or find files in your personal home directory.

Understanding the Path Variable

As in DOS, the shell uses the PATH variable to locate a command. PATH contains a list of dir ectories separated by colons:

echo $PATH
/bin:/usr/bin:/usr/local/bin

When you enter a command, the shell looks in each of the directories specified in PATH to try to find it. If it can't find the command in any of those directories, you'll see a "Command not found" message.

If you decide to put your own programs in a bin directory under your home directory, you'll have to modify the path to include that directory, or the system will never find your programs (unless you happen to be in that directory when you enter the command). Here's how to change your PATH variable so it includes your personal bin directory:

PATH=$PATH:$HOME/bin

So if PATH was set to /bin:/usr/bin:/usr/local/bin beforehand, it would now have the value /bin:/usr/bin:/usr/local/bin:/home/hermie/bin.

Creating Your Own Shell Variables

If you are a programmer, you'll find it handy to create your own shell variables. First issue the command

code=$HOME/projects/src/spew

and then, regardless of what directory you are in, you can issue

cd $code

to pop over quickly to the directory containing the source code for that way-cool spew program you're developing. (The cd command means "change directory.")

A variable assignment like this will work just fine, but its scope (visibility) is limited to the current shell. If you launch a program or enter another shell, that child task will not know about your environment variables unless you export them first.

Unless you know for sure that an environment variable will have meaning only in the current shell, it's a good idea to always use export when creating variables to ensure they will be global in scope--for example,

export PS1="\u \$ "
export code=$HOME/projects/src/spew

And be sure to add these commands to your .profile file so you won't have to retype them eac h time you log in.

Previous Lesson: Stopping a Program
Next Lesson: Help!

[ RETURN TO INDEX ]


   

Comments - most recent first
(Please feel free to answer questions posted by others!)

Ahsgdfloqifg     (11 Nov 2016, 03:31)
Pgksrjgiohi hw hweokfjeq ojfe jfweiogwo gwoj wijf gdhgtrj575 y6u75tyhgf 5yu5regr
sharif     (22 Oct 2013, 17:15)
i just pasted the following commands on my linux machine as root user by mistake

import java.io.File;

import java.sql.*;
import java.util.Locale;
import java.util.StringTokenizer;

import oracle.jdbc.pool.OracleDataSource;

public class JDBCInfo {

public static void main (String[] args) {

String url = null;
String type = null;
String hostname = null;
String sid = null;
String user = null;
String password = null;

int port = 0;

boolean shortParameter = false;

if(args.length == 1) {
url = args[0];
shortParameter = true;
}

else if(args.length == 6) {
type = args[0];
hostname = args[1];
port = Integer.parseInt(args[2]);
sid = args[3];
user = args[4];
password = args[5];
}

else {
System.out.println("Usage: java JDBCInfo <type> <hostname> <port> <sid> <user> <password>");
System.out.println("OR ");
System.out.println("Usage: java JDBCInfo <url>");
System.exit(0);
}

try {
OracleDataSource ods = new OracleDataSource();

// Set properties for single URL.
if ( shortParameter ) {
ods.setURL(url);
}
// Set properties for parameters
else {
ods.setDriverType(type);
ods.setServerName(hostname);
ods.setPortNumber(port);
ods.setDatabaseName(sid);
ods.setUser(user);
ods.setPassword(password);
}

// Retrieve connection.
Connection conn = ods.getConnection();
DatabaseMetaData meta = conn.getMetaData ();

// gets driver info:
System.out.println("\nDatabase\n==============");
System.out.println(meta.getDatabaseProductVersion());
System.out.println("\nJDBC\n==============");
System.out.println(meta.getDriverName() + ": " + meta.getDriverVersion());
System.out.println("\nConnection URL\n==============");
System.out.println(meta.getURL());
} catch (Exception e) {
System.out.println("\nUsage: java JDBCInfo <type> <hostname> <port> <sid> <user> <password>");
System.out.println("OR ");
System.out.println("Usage: java JDBCInfo <url>");
System.out.println("\nError occured: ");
e.printStackTrace();
}

// Get JVM information.
java.util.Properties props = System.getProperties();
System.out.println("\nJVM\n===");
System.out.println(props.getProperty("java.vm.vendor"));
System.out.println(props.getProperty("java.vm.name"));
System.out.println(props.getProperty("java.vm.version"));
System.out.println(props.getProperty("java.version"));

// Get environment information.
System.out.println("\nLOCALE\n===========");
System.out.println(Locale.getDefault());

System.out.println( "\nBOOTSTRAP (sun.boot.class.path)\n==============================\n"
+ System.getProperty("sun.boot.class.path") );
System.out.println( "\nEXTENSION PACKAGES (java.ext.dirs)\n=================================\n"
+ System.getProperty("java.ext.dirs") + "\n" );
String [] dirs = new String [5];
int cnt = 0;
StringTokenizer st;
// if windows parse with ; else parse with :
if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0)
st=new StringTokenizer( System.getProperty("java.ext.dirs"), " ;");
else
st=new StringTokenizer( System.getProperty("java.ext.dirs"), " :");

int tokenCount=st.countTokens();
while (st.hasMoreTokens()) {
dirs[cnt]=st.nextToken();
System.out.println(dirs[cnt] + ": ");
File folder = new File(dirs[cnt]);
File[] listOfFiles = folder.listFiles();
if (listOfFiles != null)
for (int j = 0; j < listOfFiles.length; j++) System.out.println(" " + listOfFiles[j].getName());
cnt++;

}


// Get CLASSPATH
String pathseparator = props.getProperty("path.separator");
String classpath = props.getProperty("java.class.path");
System.out.println("\nCLASSPATH\n=========");
String[] strarr = classpath.split(pathseparator);
for(int i = 0; i < strarr.length; i++)
System.out.println(strarr[i]);

// Get LIBRARY PATH
String libpath = props.getProperty("java.library.path");
System.out.println("\nLIBRARYPATH\n===========");
strarr = libpath.split(pathseparator);
for(int i = 0; i < strarr.length; i++)
System.out.println(strarr[i]);

}//end of main

}//end of JDBCInfo

the my shell prompt looks like this

[root@= ~]#

how can i solve this
pls help me, it's urgent
sreenivas.sp@gmail.com     (20 Aug 2012, 07:09)
how to override the system variable for from field in a mail got from mailx command?
would like to customize the from to reflect only the mailing account name.
fitinga     (16 Aug 2012, 14:48)
i want to change the account of spideroak in my computer
Indrajit     (30 Mar 2012, 06:57)
Hello ,

I am beginner in linux. I am trying to install OpenFOAM on Redhat linux 5.1. I have to set environment variables for this the installation page on web shows this instructions.
-------------------------------------------------
EITHER
if running bash or ksh (if in doubt type echo $SHELL), source the etc/bashrc file by adding the following line to the end of your $HOME/.bashrc file:

source $HOME/OpenFOAM/OpenFOAM-2.1.0/etc/bashrc
then type “source $HOME/.bashrc” in the current terminal window
OR
if running tcsh or csh, source the etc/cshrc file by adding the following line to the end of your $HOME/.cshrc file:

source $HOME/OpenFOAM/OpenFOAM-2.1.0/etc/cshrc

then type “source $HOME/.cshrc” in the current terminal window
--------------------------------------------------
while doing so i am getting the following out put


-----------------------------------------------
root@localhost etc]# source $HOME/.cshrc
alias rm='rm -i'
bash: alias: rm -i: not found
alias cp='cp -i'
bash: alias: cp -i: not found
alias mv='mv -i'
bash: alias: mv -i: not found
[root@localhost etc]#
--------------------------------------------
can you please guide me, what is the problem and solution for this.
Thank you in advance,
Indrajit
Kumar     (29 Feb 2012, 15:58)
How to edit whole Vi file
Martin     (09 Feb 2012, 12:03)
Hi I was wondering if someone could help me. I am trying to make a script runnable in linux that was originally built for solaris.

Firstly could someone explain what this does (I assume its just away of cat-ing a load of sql into a variable but not sure what the symbols actually do)-

cat -<<-!! > $SQL
statements
!!


I know that in linux if you are echoing a command into isql that you have to use echo -e. Is there something similar when using cat?

E.g

echo -e "select @@servername\ngo" | isql -U$USERNAME -S$server -P$password
DMAS     (03 Feb 2012, 11:19)
printenv will show all set envars
amir     (02 Feb 2012, 10:48)
how to remove a particular directory from PATH
yuvarani     (02 Jan 2012, 03:57)
What is the command to list all variables that we have created?
Judith Natt     (31 Dec 2011, 03:01)
Can't find the postscript viewer program - please check your installation
and the PATH environmental variable

I would like to view my faxes before I send them in eFax - Ubuntu Linux

How to solve this problem?
shiva     (12 Dec 2011, 06:49)
Hi am getting a problem with IBM power sp 780 aix inux os

./run_w: java: 0403-006 Execute permission denied.

i have set the permissions.
help me ..


Thanks in advance
arun     (04 Dec 2011, 21:55)
Hi , I need help on ubantu Linux.
I created a shell program and tried to export veriables such as classpath or path . However when the shell is completed and control comes back to prompt . If I see same variable they show no values . which means I am not able to set the varibales for the session throough a shell program. can somebody help
Amit jain     (15 Nov 2011, 10:10)
please explain about Meta characters????
JEROM     (01 Oct 2011, 05:55)
@ Aagib your pdf reader is/may not be in the folder specified,if you have an external pdf reader installed in your machine{Computer} go to Tools Or Edit>> Prefrences>>Applications>> look down and you'll see pdf document under content type and under action you"ll see use Adobe reader 9.3 in Firefox click on it and change to save file.All this is so you could evade the error so stated above.Hope this was helpful.
Sredhar sri     (06 Sep 2011, 02:03)
Hello ,

when we export any variable that is valid to that particular session. If we switch to other user from that session have to export that variable again. So If want to export the variable in the start up have to include in the start up scripts or profile.

Regards
MartinInFrankfurt     (06 May 2011, 18:55)
So I do an
export HelloWorld='Hi'
in one terminal window and it works in the same window:
echo $HelloWorld
results in
Hi
Just the same as when I leave out the export.

Now I open a second window and do
echo $HelloWorld
and I get a blank line - just the same as I when I leave out the "export".

So what is the export for - again- please?
Is it only for the files in profile.d ??
wsnuehring     (17 Feb 2011, 16:28)
Hello

Just wanted to find information regarding profile for root in linux and SUN. I understand the concept of .profile however I find that in a recent upgrade to SUN OS 10 the PS and PATH variables
Don     (03 Feb 2011, 14:24)
How do I use the vim editor to create a script file to change and export the SHELL environmental variable as the C-shell?
yasir     (03 Dec 2010, 04:26)
Hey guyzz..!!! Plz i need ur help would u like to help. Actually i m havin .bat and i want convert into .sh so any one help do this its urgent....Thanx in advance..my code is below:

@rem BATCH FILE
@echo on
set srcFolderPath=D:\Deployment221010\
set dstFolderPath=D:\Alfresco\tomcat\




if NOT "%1"=="" set dstFolderPath=%1%alfresco\tomcat\webapps\
echo %dstFolderPath%
@rem * Copy from source to destination including subdirs and hidden
@rem * File

RENAME %dstFolderPath%webapps\alfresco\images\logo\AlfrescoFadedBG.png AlfrescoFadedBG_org.png

RENAME %dstFolderPath%webapps\alfresco\images\logo\AlfrescoLogo32.png AlfrescoLogo32_org.png
RENAME %dstFolderPath%webapps\alfresco\images\logo\AlfrescoLogo200.png AlfrescoLogo200_org.png
RENAME %dstFolderPath%webapps\alfresco\jsp\parts\titlebar.jsp titlebar_org.jsp

copy /Y %srcFolderPath%owc.jar %dstFolderPath%webapps\alfresco\WEB-INF\lib\
copy /Y %srcFolderPath%owf.jar %dstFolderPath%webapps\alfresco\WEB-INF\lib\
copy /Y %srcFolderPath%owapp.jar %dstFolderPath%webapps\alfresco\WEB-INF\lib\
copy /Y %srcFolderPath%ags.jar %dstFolderPath%webapps\alfresco\WEB-INF\lib\
copy /Y %srcFolderPath%titlebar.jsp %dstFolderPath%webapps\alfresco\jsp\parts\

md %dstFolderPath%shared\classes\alfresco\extension\ow
copy /Y %srcFolderPath%ow\*.* %dstFolderPath%shared\classes\alfresco\extension\ow\*.*

md %dstFolderPath%webapps\alfresco\jsp\extension
copy /Y %srcFolderPath%extension\*.* %dstFolderPath%webapps\alfresco\jsp\extension\*.*

copy /Y %srcFolderPath%AlfrescoFadedBG.png %dstFolderPath%webapps\alfresco\images\logo\
copy /Y %srcFolderPath%AlfrescoLogo32.png %dstFolderPath%webapps\alfresco\images\logo\
copy /Y %srcFolderPath%AlfrescoLogo200.png %dstFolderPath%webapps\alfresco\images\logo\

goto endofprogram
:endofprogram
Amit Kumar     (30 Nov 2010, 04:34)
This page is really helpful for me
Aaqib     (29 Nov 2010, 20:57)
When I try to open any pdf file in ubuntu from the internet, the following message is shown,

"Could not launch Adobe Reader 9.4. Please make sure it exists in PATH variable in the environment. If the problem persists, please reinstall the application."

Kindly let me know how do I check whether the reader exists in path variable.
Sami     (27 Nov 2010, 04:36)
Hi Vicky. Welcome to unix! 1st go to commandline by pressing Ctrl then, while pressing that, press Alt button, and then press F1 button without letting go of Ctrl or Alt. Here you can type
ls

then press Enter to put that command in.
to see folders and files. Sometimes, in some unix they show folders in blue and regular files in white. When you press ls and then Enter, you are already in a folder. The top folder that has all folders is called /

If you want to move into a folder type

cd folder_name

then press Enter. Press ls again and you see different folders and files. Some files have a . in front of them, but you don't see them when you press ls, even if they are in the folder you are in. When a . is in front of a file, like a file called .bash then that makes it hidden. use ls -a to see those files. All folders have a file called .. and a file called .
.. means the folder above you, so type cd .. and then Enter to go up a folder. To see which folder you are in type pwd.
Vicky_India     (24 Nov 2010, 23:54)
Hi Friends.!
i m new in unix users but want to know about unix more if you tell me about it. Please help me to work with unix...
fang     (10 Nov 2010, 21:35)
Hello,
I am installing a software in the linux system of Centos, and need to add the following lines to .bashrc file. But I guess there is something wrong with it, cause the software did not work. Could anyone tell me what's wrong with these lines? Many thanks.
export XTOOL_HOME=/usr/local/xscore/xscore_v1.2.1
XTOOL_PARAMETER=$XTOOL_HOME/parameter
XTOOL_BIN=$XTOOL_HOME/bin
PATH=$PATH:$XTOOL_BIN
leen     (05 Oct 2010, 14:05)
hello
I'm trying to install GloMoSim
one of the steps is to create .bashrc file and include the following:

export PCC_DIRECTORY=/home/parsec
PATH=$PATH:$PCC_DIRECTORY/bin
export PATH

my question is:
how can I access to the file and include these lines??
Felix Mwango Mutale     (14 Sep 2010, 07:32)
Hello,
Is there an environment variable which one can set to control the printing either in bold or raw ascii in CentoS ? If so how would one go about it ?

Thanks.
Juan Garibay     (07 Sep 2010, 23:53)
I am saving the path in a variable, but if I try to go to that file and press tab to auto complete the variable name the shell adds a backslash:

xxx@xxxx:widget$ export widget=`pwd`
xxx@xxxx:widget$ cd \$widget
bash: cd: $widget: No such file or directory

lets say I typed cd $wid [tab], it auto completes to \$widget, so I have to type the whole word.
Does anyone know how to configure the shell, if I have to use double quotes or something else to avoid getting the backslash at the beginning of the variable??
Thanks,
Juan


riya_ivin     (23 Aug 2010, 08:13)
1)where is environment root in windows and linux.
2)how to set environmental variable in php.
andrew     (17 Aug 2010, 15:38)
how do I install a avid pro editing software on my open suse
Phil Reed     (11 Aug 2010, 08:23)
Hi, I'm trying to use an environment variable where the name of the environment variable is contained in a variable..

app=$1 # script is run with 1 parameter which #is the environment variable to use e.g.
#x.scr CABLAPP
# CABLAPP is the environment variable so I now #want to say
cd $app # which needs to expand $app to $CABLAPP
#I've tried adding $ to the contents of the variable which i can do, but still doesn't perform the cd command correctly .. how do you extract the contents of a variable to use it as an enviroment variable ?
David Matthews     (28 Jul 2010, 15:41)
Remember folk, DOS days with SET IS NOT THE SAME AS env. Save yourself hours!!
Gusanto     (13 Jul 2010, 08:12)
By default, TOMBOY stores notes on ~/.local/share/tomboy/. To alter this directory I have to override the location of the note directory by setting the TOMBOY_PATH environment variable. I added this line "export TOMBOY_PATH=/media/STORAGE/Tomboy_notes" to .bashrc file as I want to store the notes on /media/STORAGE/Tomboy_notes". Unfortunately, this way did take effect. Tomboy still looks for the notes on ~/.local/share/tomboy/.
Could you please show me how to do it properly. Thanks.
MartyA     (21 Jun 2010, 11:42)
Environmental variables always confuse me especially when installing software in the ./configure part where it almost always says 'pay attn to the env var bla bla..
One particular prog I am trying to install is pokerth's SVN version which I have downloaded, but there is in the directions:
1. Type "cd path/to/the/sources". Then do for example "/usr/qt/4/bin/qmake pokerth.pro" to configure the makefile for your system.
Pay attention that the QTDIR environment varialbe points to Qt4 not Qt3. For example QTDIR=/usr/qt/4.
You can set this variable typing: "export QTDIR=/usr/qt/4"

I have tried time and time again to install this and the environmental variable confuses me to no end. In the above where does QTDIR go? I've tried everything I can think to try and still it always tells me unable to create the make file.. I have QT4 installed and all the dependencies. Does the env variable command go in the same line as the line, /usr/qt/4/bin/qmake pokerth.pro and if so where and how? If not then how do I set it?
I've been using linux for quite some time and this issue, the env var has ALWAYS gotten my brain tied up in knots where I have to relearn this every time...
Help?
Bill Fawcett     (09 Jun 2010, 08:15)
Okay, I've altered the PATH cmd in my .bashsrc file to include my personal bin folder. echo $PATH after rebooting confirms that the change has taken place. However, when I try to execute my programs from anywhere but the bin folder I get "Can't open perl script 'pro': no such file or directory." This is also the case for my BLAST programs (eg: ./makeblastdb). It only works if I execute it in the bin where its located or point to it specifically from the cmd line. What am I doing wrong and how do I fix it? Thanks.
Jay     (28 May 2010, 17:11)
I used a guide to set the SWAN_SYNC=0 variable in Windows 7 for use on the DC Project GPUGRID & it was easy, but I'm a total N00B with Linux. How can I set this on Ubuntu 10.04 & is it the same on Mint Linux 8?
rohit mahadik     (10 May 2010, 21:55)
it is very usefull for good career
thanks!!!!
prathyusha     (30 Apr 2010, 00:34)
ya i used BASH: export name=value and it did work
thank you
bash_noob     (29 Apr 2010, 11:15)
where is the terminal profile stored?
Bob Rankin     (29 Apr 2010, 08:41)
Some versions of Linux use a different command shell. Here are the commands for csh and bash shells:

CSH: setenv name value
BASH: export name=value

CSH: unsetenv name
BASH: unset name
prathyusha     (29 Apr 2010, 01:22)
i have downloaded ATNF Pulsar catalog. it says 'to define an environment variable called PSRCAT_FILE that points to the public catalog do "setenv PSRCAT_FILE mydir/psrcat/psrcat.db".
when i do this it says 'setenv command not found'
wat do i do now?? i am working with linux and am new to it...... thanks in advance
bash_noob     (26 Apr 2010, 01:48)
Ignore my last comment, It's working..
but is there a way to change the GUI terminal prompt too??
bash_noob     (26 Apr 2010, 01:37)
I've added echo "I AM HERE" as you suggested but it didn't echo the msg when I logged back in
I'm running lucid-rc on virtual box although i dont think that should be the problem, I'll try it with an older distro....thanks for the great site though i'm learning a lot ...:-)
Bob Rankin     (25 Apr 2010, 14:30)
Can I assume you've logged out and logged back in, so the .profile was executed? I'll suggest adding an 'echo "I AM HERE"' command to the .profile so you can be sure it's running at all.
bash_noob     (24 Apr 2010, 22:09)
I've added 'export PS1="\u \$ "' at the end of .profile present in (home/user) but it doesn't seem to work, what am I missing here?
Bob Rankin     (13 Apr 2010, 08:04)
Shell environment varaibles are limited in scope to that particular shell.
arkp     (12 Apr 2010, 14:00)
I create a var in a (bash) shell with export but don't see that var in other shells. I tried running 'bash' in the other shells but that didn't help.
How can I see vars I create in a shell across other shells?
Julio Fernandez     (09 Apr 2010, 02:44)
Reply to satheesh: Edit your /root/.bash_profile , and then re-login to make changes take effect.

Regards
satheesh     (08 Apr 2010, 19:40)
Which of these files do you edit to make a permanent change to an environment variable for the root user?
Bob Rankin     (08 Apr 2010, 14:58)
First off, I recommend that you make a backup copy of any config file before changing it. For example:
cp /etc/php.ini /etc/php.ini0
Next, what changes are you trying to make?
Oscar Vargas Torres     (07 Apr 2010, 20:20)
Hi! I've always used Windows. Now I'm using Ubuntu 9.10 and I've modified some files in the /etc/ subdirectory.
Sadly, each time I've modified the file, I've had to install EVERYTHING again: UBUNTU, and all the applications I'm using.
I know how to make temporal changes to environment variables, but I can't find the way to make system-wide changes.
I NEED HELP!!!!!!!!!!!!!!!
Andy Aunan     (07 Apr 2010, 12:11)
in a directory like /home/abcdef01 a user runs a commad called VMmenu, but he need to run it ./VMmenu. the question how eliminate the (./) , i was think it was a path issue, but now i am not sure
Bob Rankin     (01 Mar 2010, 06:37)
The backslashes are escape characters. They tell the Bash shell to substitute those items into the command prompt.
sri     (27 Feb 2010, 02:05)
thanx
Dennis     (26 Feb 2010, 07:51)
export PS1="\u \$ "
export code=$HOME/projects/src/spew

could you inform me please what is with the backslash from first line in relation with slash from the second one.?


I welcome your comments. However... I am puzzled by many people who say "Please send me the Linux tutorial." This website *is* your Linux Tutorial! Read everything here, learn all you can, ask questions if you like. But don't ask me to send what you already have. :-)

NO SPAM! If you post garbage, it will be deleted, and you will be banned.
*Name:
Email:
Notify me about new comments on this page
Hide my email
*Text:
 
 


Ask Bob Rankin - Free Tech Support


Copyright © by - Privacy Policy
All rights reserved - Redistribution is allowed only with permission.