For any command or script, by default, the shell checks locations specified by the PATH variable. To run our script from anywhere, we need to add its location to the PATH variable. This can be done in two ways:
This method is temporary and works only for the current terminal session.
Steps:
-
Check the current
PATHvariable value:durgasoft@durgasoft:~/scripts$ echo $PATH /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
-
Add the script's location to the
PATHvariable:$ export PATH=$PATH:/home/durgasoft/scripts
-
Verify the updated
PATHvariable:durgasoft@durgasoft:~/scripts$ echo $PATH /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/home/durgasoft/scripts
Now, you can run your script without specifying its path:
$date.sh
The current System Date and Time:
Wed Dec 4 21:01:49 IST 2019Note: These changes are temporary. They will be lost once the terminal session is closed.
This method ensures the changes persist across terminal sessions.
Steps:
-
Open the
.bashrcfile located in your home directory:nano ~/.bashrc -
Add the following line at the bottom of the file:
export PATH=$PATH:/home/durgasoft/scripts
-
Save the file and exit. Apply the changes by running:
source ~/.bashrc
Now, your script's location is permanently added to the PATH variable.
Q5 What is the Meaning of a Startup File?
.bashrcis a startup file that is executed automatically when a new terminal session starts.- To perform specific tasks (e.g., creating aliases, updating the
PATHvariable), you can define them in this file.
Q6 What is Meant by a Logout File?
.bash_logoutis a logout file that is executed automatically when the terminal session exits.- To perform specific tasks (e.g., cleanup activities) during terminal exit, you can define them in this file.
The .bashrc file is typically located in the home directory of your user account. You can find it using the following methods:
The file is located at:
~/.bashrcHere, ~ represents your home directory (e.g., /home/username on Linux systems).
To confirm its presence, run:
ls -a ~ | grep .bashrcThis will list .bashrc if it exists.
To edit the file:
nano ~/.bashrcTo view the file:
cat ~/.bashrcIf the .bashrc file is not present, you can create one:
touch ~/.bashrc