3

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?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255

2 Answers2

4

How the insides works if a command exists: It's just useing plain regular standard input to store the commands -either from script or not- and its arguments, then parses them so they can be sent to a system call like execve that will find the command in the system then run it:

http://man7.org/linux/man-pages/man2/execve.2.html

Besides, like Time4Tea said, there's some builtin commands that are exclusive to the shell you're running. exit is one of them.

 

As a rule of thumb, if there's something about Linux you can't know by any regular means, just go for its source code.

X.LINK
  • 1,314
3

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.

Time4Tea
  • 2,366