How Does a Simple Linux Shell Take Commands?

Cody Paral
2 min readMar 27, 2018

--

To understand how a shell works I will use the command “ls -l”, However we should first talk about what a shell is. A shell is a program that takes user input from the keyboard and passes it to the operating system. If something is not found or doesn’t exist in the operating system the shell should warn the user that what they are looking for cannot be found.

When a user types “ls -l” in the shell and hits enter, the shell does multiple things. The first thing it does is read the user input. The user input is then saved to a buffer, this is the easiest way for a computer to store user input. Then the user input is Tokenized. Tokenizing a buffer will separate it into individual strings, it does this by separating everything by a delimiter. The delimiter is usually spaces, newlines, and tab (this way files passed to the shell can be read correctly).

After the shell tokenizes the buffer it will return an array of pointers to strings. This is useful for a couple different reasons, the main reason being that you can reference each item in the buffer individually. This is important because the first item you would want access in the case of “ls -l” is “ls”. That is because the shell will make a “system call” asking the operating system to perform “ls”. The shell makes this system call with the execve() function. To allow the operating system to perform two tasks at once it will start a child process and run the execve function in it. This function takes in a couple parameters, the first being the command to ask the operating system to perform. The second parameter is everything that comes after ls on the command line. That is because the function will pass everything that comes after “ls” to “ls”.

The next important thing for the shell to do after executing the command is to restart the process. That is because the shell is interactive which means it should handle a command the user put in, execute it and the go back to take more commands. That being said after the shell executes the command with the execve() function the child process ends and the loop restarts and the user is prompted for input again.

--

--