Type ‘ls -l *.c’, and you’ll see only C.

Diego Acosta
3 min readDec 8, 2021
And God said, “ls -l *.c”, and there was a list of .c files.

In next lines, you’ll understand what’s behind the magic of writting a simple command in UNIX.

If you’re in a UNIX system, you have a lot of useful commands to run in the CLI (Command Line Interpreter), even you can combine them properly to get the result that you’re looking for. Some command accepts orders to run in a specific way. Today we’re going to focus on one of the most used commands, ls and one of its many orders: -l.

$ ls

The command ls list the files in the current directory

$ ls -l

Then, if the order -l is added, the command will list the same content but with another format (in this case, a long format)

$ ls -l *.c

At last but not least, adding the *.c to the previous line, will list only the files that their names end with .c

Easy, right? Now let’s analyze the behind the scenes of all of this.

  1. Reading the input
    Inmediately the user wirtes an input and hits Enter, the system takes it to the getline() function, which makes a system call (read) to the STDIN (stands for standard input) and then saves it as a string in a determinated buffer.
  2. Split it!
    Now the whole input is splitted into tokens and it’s copied into an array of strings. This is possible thanks to the strtok() function, which receives the string to be splitted, and a list of delimiters, which define what characters will split the input string into tokens.
  3. Aliases or Built in?
    With the input splitted into tokens, the system checks if the commands entered are aliases and changes them if any are found. To start the execution, it first checks if the first token of the list is built-in function. If it matches, it will execute the given function and it will return the prompt and it’ll wait for the next input.
  4. PATH
    If the command isn’t a built-in function call, system needs to check if the command is calling one of the many system functions that are found as executables files in the directories shown in the $PATH enviromental variable. To do it, first tries to execute the command as it’s tokenized. If fails, then the command is concatenated to the different directories of path looking if it matches to any of the standard executables (for ls command it’s /usr/bin/ls). When there’s a match, it’ll execute the file with their respective arguments if passed, of course (-l and *.c in this case).
  5. No matches :(
    If all directories in $PATH are checked and there’re no matches for the command, shell will display an error message about the file or directory not being found.

Authors:
- Diego Acosta
- Ignacio Castellán García

--

--

Diego Acosta

Software Engineer Alumni @ Holberton School - MVD->UY