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.

| improve this answer | |
  • 1
    Also, aliases and functions. These override built-ins. – Kusalananda Feb 8 '18 at 12:10

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:


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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.