Living With Linux – Scripting For $PATH

Posted: 10th September 2011 by Mike Trent in Computer, Linux
Tags: , , , , ,

In the last post  “Living With Linux – Scripting For Files And Folders,” I described how to write a simple script for checking if a directory/folder existed and if not, create it.  This is fine, but what if you needed to run a script within that folder from the command line and you didn’t want to have to go to that directory or enter the path every time you ran the script?  As I searched the internet for advice on making to path permanent, but had no immediate success.

There were pages and pages of posts that only gave the directive which produced a temporary setting.  Fortunately there was one link which had the answer that I was looking for.  If you have done an internet search, you probably found only the advice that tells you how to set the path using the following code from within the terminal:  PATH=$PATH:~/<new folder>   Well this is fine, but it is only temporary.  Every time you close the terminal window, that path vanishes.  Try this test; create a new directory by opening a terminal window and at the prompt enter:  mkdir myNewDir

Now enter:  echo $PATH

The PATH contents will print out on your screen.  As expected, the directory mytest is not in the readout.

Now you will enter:  PATH=$PATH:~/myNewDir

Again enter:  echo $PATH

As you’ll notice, your new folder is now listed in $PATH.  Shut down the terminal and reopen it anew.  Again echo PATH to see if the folder is still in the listing.  No?  That’s because when you shut down the terminal and restarted it, bash read the PATH listing from the bashrc file which you never modified.  So, how to make this permanent? You will be reusing the script file from the last post and editing it.   Open myTest and edit it so that it matches the following and save it:

#!/bin/bash
# myTest script
# This script adds a permenet path to bashrc
clear
echo

echo 'export PATH=$PATH:~/myNewDir' >> ~/bashrc
clear
echo $PATH

Now run the script from the terminal:  ./myTest

‘export’ is a bash command and ‘PATH=$PATH:~/myNewDir’ is the object to be exported.  ‘>>’ is a directive.  ‘~/’  tells bash to look in the home folder, and ‘bashrc’ is the file the new path is to be exported to. $PATH is the current contents of bashrc which get loaded into path along with the new string ‘:~/myNewDir’  (~/ tells bash to include the home folder as part of the string, i.e. /home/mike/myNewDir)

Until next time, happy coding.

Comments are closed.