This is more of a general question I have been curious about but put simply: how does bash execute commands given to it via a script or terminal?
It would be possible, I guess, to have a bunch of if statements checking all commands like so (Pseudocode):
if (command == "pwd") pwd();
else if (command == "echo") echo();
...
But this would create problems as you would have to recompile the code every time you add a new command, like one started for a program like firefox or gedit.
Then I remembered the which
command, which (no pun intended) points to the directory of a given command, making me assume that bash simply looks for a file and grabs it with an iostream to execute it.
Is this the case, and if so, how does it know what method to call, or are they simply generic executables?
Basically, some commands are built in to the bash shell program itself (e.g. echo, set), in which case, bash already has the code compiled into it to run those commands internally, in response to a user calling them from the command line. If you look at the manual in man bash
or info bash
, it has a list of the 'builtins'.
If a command is not found in the builtins, then the shell searches the directories listed in the $PATH environment variable (in the order listed), to see if it can find an external command there. If not, then it will report an error that the command can't be found.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments