How to Set Relative Directory to PATH Variable and Run Scripts Globally

bashpath

I have some some scripts in a git project I wan to access globally, so I add the relative path to the scripts folder like so

vim ~/.bash_profile
export PATH="~/git/scripts/:$PATH"
source ~/.bash_profile

and there is a file ~/git/scripts/ called echoHelloWorld.sh, so how I can I run echoHelloWorld.sh if I am for example in the ~/Downloads folder? Do I do

cd ~/Downloads
./echoHelloWorld

because I have tried that, but it does not work, and I have also tried chmod +x echoHelloWorld.sh with no results.

Best Answer

TL;DR

Your path statement in ~/.bash_profile should look like this:

PATH=$PATH:~/git/scripts/

The basics.....

There are three problems with the way you wrote it:

  • Shouldn't use the export function since the variable (PATH) is already in the environment. When you logged in, the PATH variable was created and set. You don't need to export it as it already exists.

  • Remove the double quotes. Double quotes cause the path to be read literally so the ~ home directory expansion never takes place. For tilde expansion to work, it can't be enclosed in quotes. If you want to verify this, at the command line type the following:

    $ PATH="~/git/scripts:$PATH"
    $ echo $PATH
    ~/git/scripts:/opt/local/bin:...                  <====== INCORRECT RESULT
    
    $ PATH=~/git/scripts:$PATH
    $ echo $PATH
     /Users/foouser/git/scripts:/opt/local/bin:.....  <====== CORRECT!
    
  • Your tilde expanded (personal home directory) paths should be at the end of your path statement. Your path is read from left to right, taking precedence as it goes. In other words, if there is a command/function in your home directory with the same name as something already in your PATH it will be executed (found) first and may have unintended consequences.

Once you make the change to your ~/.bash_profile you can restart your session or just source it as you did before and the changes will take place. You can confirm that it worked by issing either (or both) the following commands:

$ echo $PATH
$ which echoHelloWorld.sh

The first will output the PATH as set and the second will tell you where in the path it found your script.