WHAT HAPPENS WHEN YOU TYPE “ls -l *.c” ?

Montassar Barbouchi
3 min readDec 8, 2021

--

First let’s clear something:

  • ls : list all files.
  • -l : option for the “ls” command to use the long list format.
  • * : an asterisk matches one or more occurrences of any character, including no character.
  • .c : files with the “.c” extension is a plain text C/C++ source code file.

So what will happen when you type “ls -l *.c” :

The “ls -l” part will list all the files in the directory with the long list format.

The “*.c” part will search for all the files with the extension (.c).

When you type “ls *.c” all the (.c) files will be displayed and if you add the “-l” option the output will be the same but with the long list format.

But, what really happens when we type ‘ls -l *.c’ and press enter?

  • Feeding the command to the bash! : After ls is entered, the keyboard driver realizes that characters have been entered and pushes them to the shell. The string is passed as one single string .This is then split into tokens by excluding the white spaces. Our command has now two tokens, ‘ls’ and “-l” and ‘*.c’.This is placed in an array of strings. This whole process is known as Tokenization.
  1. Now that the array is tokenized, we need to see if each token has an alias assigned. If an alias is found it is stored as a token after removing the spaces like before and again it is checked for aliases.

2. Next, the computer checks if tokens are built-in functions or not. If the command is a built in, the shell runs the command directly, without using another program. For example, ‘cd’ is a built in; however, ‘ls’ is not a built in , so now system needs to find the executable or program for ‘ls’.

3. Interpreting and finding the executable for the command : After that, the bash interprets the command. The first search for the command ‘ls’ is done through $PATH. $PATH is an environmental variable which holds the paths of all executable programs. The search calls a series of functions like find_user_command() ,find_user_command_in_path , find_in_path_element. Each path in the PATH variable is searched for the executable that corresponds the command ‘ls’. BASH invokes the function stat() to check if there is a matching executable in each path.

4. Pulling the executable to memory : After all these, when when the file is located at ‘/usr/bin/ls’ , BASH performs execve() command to run the file.

We acknowledge the articles written by Davoud Shafiee by as our guide to get into the matter.

AUTHORS:

Montassar Barvouchi

Rayen Hedri

--

--