- Learning Linux Shell Scripting
- Ganesh Naik
- 414字
- 2021-06-25 22:02:53
Learning shell interpretation of commands
When we log in, the $ sign will be visible in the shell Terminal (# prompt if you are logged in as the root or administrator). The Bash shell runs scripts as the interpreter. Whenever we type a command, the Bash shell will read them as a series of words (tokens). Each word is separated by a space ( ), semicolon (;), or any other command delimiter. We terminate the command by pressing the Enter key. This will insert a newline character at the end of the command. The first word is taken as a command, then consecutive words are treated as options or parameters.
The shell processes the command line as follows:
- If applicable, the substitution of history commands
- Converting the command line into tokens and words
- Updating the history
- Processing quotes
- Defining functions and substitution of aliases
- Setting up of pipes, redirection, and background
- Substitution of variables (such as $name and $user) is performed
- Command substitution (echocal and echodate) is performed
- Globing is performed (filename substitution, such as ls *)
- Execution of the command
The sequence of execution of different types of commands will be as follows:
- Aliases (l, ll, egrep, and similar)
- Keywords (for, if, while, and similar)
- Functions (user-defined or shell-defined functions)
- The builtin commands (bg, fg, source, cd, and similar)
- Executable external commands and scripts (command from the bin and sbin folder)
Whenever a command is typed in a shell or terminal, the complete command will be tokenized, and then shell will check if the command is an alias.
Aliases, keywords, functions, and builtin commands are executed in the current shell and, therefore their execution is fast compared to executable external commands or scripts. Executable external commands will have a corresponding binary file or shell script file in the file system, which will be stored in any folder. The shell will search for the binary file or script of a command by searching in the PATH environment variable. If we want to know what type of command it is, such as if it is an alias, a function, or internal command, it can be found out by the type builtin command, which is shown as follows:
$ type mkdir mkdir is /usr/bin/mkdir $ type cd cd is a shell builtin $ type ll ll is aliased to `ls -l --color=auto' $ type hello hello is a function hello () { echo "Hello World !"; } $ type for for is a shell keyword