What happens when you type ls -l?

The ls command is one of the most basic built-in commands that comes with shell. The main purpose of ls is to list all the files in your current directory. There are tons of modifiers that can come after ls but the one we will be focusing on today is -l.

This is what the default ls command looks like

The first thing we need to focus on is what happens when we type a command into the shell. Let's say we go into a shell and type ls -l. The first step of reading our command is to take both parts of the argument ls and -l and split them up. We can do this with the getline() function. The main reason we want to do this is so we can search for the ls command by itself because it is not stored with a modifier.

Now that we have separated the ls and the -l modifier the shell would search for aliases (an alias is a shortcut for a command. For example running l instead of ls) then would proceed to look for built-ins (commands that are built straight into the code. One example is the exit command). We can now search for the executable of the ls command. The first thing we should do is obtain the path. The path usually looks like the picture listed below.

This is the default path you will find in shell

How the path works is each set of directories is separated by a delimiter in this case it is the semicolon. What we can do with this is search each of these directories for the command we want to run. We will be using the access function to check if the executable we want is in each of the directories. After going through the path with the access function we will find that the ls executable is in the /bin path which will result in us getting /bin/ls.

After attaching the ls to the bin path we can now reattach -l to it because we no longer need to specify ls. So now we are ending with /bin/ls -l and this will run in the execve() function in order to run the ls -l command. So now finally after all the steps above are done we have out ls -l command output which should look something like the image below!

This is what the ls -l command output should look like

Now that we have our output there is one more thing that happens after we finish our command. The shell prints the $ again for you to run another command.