Understanding the PATH Variable in Bash

Postgraduate in Communications Engineering with working experience in the Support Desk and self-study in software development.
Environment variables track specific system information, such as the name of the user logged into the shell, the default home directory for the user, the search path the shell uses to find executable programs, and so on.
The PATH environment variable in Bash and other Unix-like operating systems such as Linux and macOS is a critical variable that dictates where the shell looks for executable files. When you type a command in the terminal, the shell searches through the directories listed in the PATH variable, in the order they are listed, to find the executable file that matches the command.
The directories in the PATH variable are separated by colons (:). You can view your current PATH setting by running the following command:
echo $PATH
How it Works
For example, suppose PATH is set as follows:

When you run a command like ls, the shell will look for the ls executable in the following directories, in this order:
/usr/local/bin//usr/bin//user/local/sbin/
If it finds ls in /usr/bin/, for instance, it will run it from there and won't search in /user/local/sbin/.
Workshop Exercises
Exercise 1: Understand PATH Priority
Open a terminal.
Type
which lsand press Enter.
The output shows the absolute path of the
lscommand. As we can see, this directory is the second one listed in thePATHdirectory.
Exercise 2: Add a Directory to PATH
Create a directory ~/scripts where you keep some of your custom scripts. To add this directory to your PATH as follows:
Open a terminal.
Run
export PATH=$PATH:~/my_scriptsConfirm by running
echo $PATH.

Note: This change is temporary and will be lost when you close the terminal. To make it permanent, you'll have to add the export command to your shell's startup file, like .bashrc or .bash_profile.
Exercise 3: Create a Custom Command
Create a new script file in the
~/scriptsdirectory.touch ~/scripts/test_command.shMake it executable.
chmod +x ~/scripts/test_command.sh
Edit the file to include the following:
#!/bin/bash echo "Hello, this is my custom command. Let's check it!"Save the file.
Try running
test_command.shfrom anywhere in the terminal. Did it work? If not, make sure that~/my_scriptsis in yourPATH.

Exercise 4: Remove a Directory from PATH
Run
export PATH=$(echo $PATH | sed 's/:\/home\/centos\/scripts//')This will remove
/home/centos/scriptsfrom yourPATH(if it exists).Confirm by running
echo $PATH.





