Have you ever think about how a command/binary executing in Linux even the command is not in your present working directory.??
What is a command/binary.!!
A command is an executable file which was written in a programming language like C, C++ and converted into machine code with compilation. These machine codes will be packaged with the package manager and we are installing it with ‘yum install ‘ or rpm ( Redhat Package Manager ). on installing packages the binaries or commands will be copied to one of the ‘bin or sbin’ directory.
Create a simple binary/command and run it.
To understand the concepts we can create a simple binary. here I’m using a basic shell command ‘echo’ to write a binary instead of writing in C or C++ and compiling it.
1. Create a text file inside a directory and write some scripts
Create a directory.
Create a File with a name. ( This will be your command)
Type the below text to the created file ( here myname ) and writeout and quite.
echo ” My Name is Shafeeq ”
2. Give excecution permission to the file
chmod 755 /mybin/mybin
3. Run your binary
It will display ‘ My Name is Shafeeq ‘. We have created a simple binary here, like this only all the commands works. But we are not typing commands with the exact path. So how do the commands works without giving exact location.?
How commands work without specifying the exact location.!
1. Check location of date and uptime commands.
Even the location of both these commands are different, They are giving us the result.
2. $PATH variable
With the use of the $PATH ( PATH Variable ), we can run commands without giving the excact location of a binary/executable file. So that we need not remember all the location of the binary. To print $PATH for the current user just type the below command.
It will show you differnt paths seperated by ‘:’ for the user.
If you type a command system will search these locations for a binary. If there are no commands with the name in those locations system will tell you ‘ Command not find ‘
3. Add a directory to $PATH
This command will add ‘/mybin’ to $PATH Variable, if you type ‘PATH=/mybin’ it will replace all the other locations. Remember This is a temporary variable definition. This changes will be reset on closing your current terminal.
Check your $PATH now.
Our directory ( /mybin ) will be added to $PATH now.
4. Run our command without giving path
Bingooo…!! It will execute the binary without giving exact location now and print ‘ My Name is Shafeeq’
5. How to add a new directory to $PATH Permanantly.
You can simply add a directory to $PATH by defining it in one of the following files
Open /root/.bash_profile in vim editor and add the definition line below the PATH=$PATH:$HOME/bin
Reload your .bash_profile file
Now our directory will be added to $PATH permanatly for root user.
Thanks for reading.!! Stay connected for new posts.