Bash Script To Add A Folder/Directory to the path in linux not working

4.7k Views Asked by At

I created a bash script to add /My_Scripts/Bash_Scripts to the default PATH of linux.

!/bin/bash
#This Script is used to add a folder/diectory to the PATH..


echo -e "\e[92m\e[1mCREATING PATH...........\n\n"
cd
mkdir My_Scripts
cd My_Scripts
mkdir Bash_Scripts
cd

export PATH=$PATH:$HOME/My_Scripts/Bash_Scripts
echo -e "\e[92m\e[1mPATH CREATON SUCCESSFUL\n \e[39m"
echo $PATH

The output of script is

root@kali:~/Desktop# bash add_path
CREATING PATH...........


PATH CREATON SUCCESSFUL

`/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/root/My_Scripts/Bash_Scripts'

but if I type echo $PATH in the terminal outside, the path is not added

root@kali:~/Desktop# $PATH
bash: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin: No such file or directory
3

There are 3 best solutions below

4
Roman Pustylnikov On BEST ANSWER

First thing - you should use echo $PATH. By simply typing $PATH you're trying to execute the command, hence the "No such file or directory error"

Next - the /root/My_Scripts/Bash_Scripts wasn't really added to the PATH. The first output you see in done inside the script, so the changes could be seen there.

The reason is that PATH will be set only in the context of the script shell, execute it as source add_path to preserve the changes in variables (but only for current shell).

If you want the variable to be persistant in all shells - add it to /.bashrc (since you're runnung as root).

4
loganaayahee On

Your changes is affected in current shell only.Put the entry in .bashrc file. It will affect the all the terminal.open the .bashrc file and add the below line and run the file -

 vim ~/.bashrc
 export PATH="$PATH:/home/username"
 ~/.bashrc 

Edit the parent shell

script.sh

#!/bin/bash 
export "PATH=$PATH:$HOME/My_Scripts/Bash_Scripts"
echo $PATH

$~ PATH=$(./script.sh)

$~ echo $PATH

/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/home/loganaayahee/My_Scripts/Bash_Scripts
5
Gowtham On

You are starting up a new bash process and PATH is only modified in the context of the new process. When this process quits, changes done in its environment do not propagate to the parent process.

Instead, you would want to modify PATH in the context of current bash process. If you want this temporarily, you may source your script. source will run in the context of the current bash process. Beware of any side effects - like cd will change the directory, exit will terminate the current bash process.

If you want this change permanently for all future interactive sessions, you can modify ~/.bashrc.

Also, the syntax of shebang is #!/path/to/program, you are missing a #.