The magic of ‘ls *.c’

0. What is the Shell/Terminal?

The shell is a program that process commands you type on your keyboard. The terminal is a program that runs a shell. So what happens in the shell when you type in ‘ls *.c’?

Input is broken up into words and operators

As the shell reads the input of the command line, in this case ‘ls *.c’, it divides the input into words and operators, following quoting rules.

Alias expansions also occur

While the shell is reading the input from the step above, the shell will also identify the first command and check if there are any aliases for the specified command. If an alias is found, then the shell will check if there are any aliases for that alias.

Perform shell expansion

A symbol or character that expands into larger text, files, and general output is called an expansion. The ‘*’ is an expansion and will find all files and directories. When there is a string or even another expansion, before or after the ‘*’, it will find all files that ends or beings, respectively, with the string.

For this example, ‘*.c’ will output all files ending with a .c. This ‘output’ is now going to replace *.c. So now our command looks something like this:

Commands are executed

Once the ‘*.c” is expanded, the shell’s next step is to perform the command. The shell starts searching for the command in the built-in functions and if it is not there, then it will find the $PATH, which is an environmental variable specifying where executable programs are located. Once found, the command is executed. In this case, our command ls will list one.c, two.c, and four.c.

Shell waits for command to complete and exits

The shell will then wait for the command to end and after doing so will exit the command.

Printing command line (PS1) and $

The default interaction prompt for the command line is called PS1 and it shows the username, hostname, and full path name of the user directory. The last step after running the ‘ls *.c’ command is printing the command line prompt again also known as the PS1.