How to build custom commands in Linux or MacOs ?
In Linux or Macos, there are pre-built commands such as sudo
chmod
, pwd
, ls
. They are built in commands. Actually I mean the their directory is already set in the variable PATH
. And PATH
is the environment variable in Linux which consists of list of directories separated by a colon (:
).
If we print the value of PATH
using the command echo $PATH
, It will show a value something like given below:
/home/oem/.nvm/versions/node/v19.8.1/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/home/oem/Documents:/home/oem/Documents/custom-commands:/usr/share/enterprise-search/bin:/home/oem/.local/bin
Any command you type in terminal and the bash will search the command through these directories defined in PATH
variable and if bash is unable to find the command after traversing all the directories, it will print command not found
.
But there are some custom commands we create but we have to navigate to a directory to execute it. But there is a way. Yes you guessed it right, we have to store the directory in a PATH
variable. But let me tell you the complete steps to achieve it:
- Create any file without any extension in a specified directory. Let’s define the file name
sample-command
. - Open this file in a text editor of your choice.
- Since we didn’t define any extension of a file, we need to define the specify the interpreter of a executable file. Like for bash script, I will use the shebang line:
#!/usr/bin/bash
. In most of the cases, bash file is stored at/usr/bin
directory. For JavaScript file executed by NodeJs runtime, I will use the directory where the NodeJs executable is stored. I will first typewhich node
and it will show me something like/home/oem/.nvm/versions/node/v19.8.1/bin/node
so the interpreter will be:#!/home/oem/.nvm/versions/node/v19.8.1/bin/node
4. Don’t forget to change permissions for a newly created file sample-command
. Use chmod +x /path/to/your/sample-command
file.
5. In the sample-command
file, write a code of your choice. For illustrative purposes, I have a sample code:
#!/home/oem/.nvm/versions/node/v19.8.1/bin/node
console.log('SAMPLE COMMAND EXECUTED');
Also save the code. And don’t forget to export the PATH to the current directory of the file. Use this command: export PATH=$PATH:$(pwd)
. It will append the $(pwd)
value (which is current directory) to the $PATH
value seperated by :
. Also save the modifed PATH (using export command) in your .bashrc
/ .bash_profile
or any other configuration file. Don’t forget to execute command for example source ~/.bashrc
. It will fetch the modified configuration
Now run the code from any directory.
If I type the command in terminal sample-command
, it will show something like this in the screenshot below:
You can also pass arguments in the command but you need to handle arguments in the source code itself. Different languages have their own ways of handling them.