Linux Basics: Linux (BASH) command execution and search mechanism

Source: Internet
Author: User
Tags aliases builtin

How is the program executed?

when the operating system starts, it waits for user action. So how does the user communicate with the operating system? How do you trigger program execution? Typically, interacting with the operating system, there are two implementations:CLI (command line interface); CUI (Graphic user interface).

For example, when we start the Windows system, we want to see a movie, listen to music, then we have to go to trigger the program shortcut to start the program.

Similarly, Linux must pass a shell program to interact with kernel. The execution of the Linux command must depend on the shell command interpreter. The shell is actually a special program running on a Linux system that sits between the operating system kernel and the user, takes care of the user input commands and interprets them, passes the required actions to the system kernel execution, and the shell acts as a "translator" between the user and the kernel. When a user logs on to a Linux system, a shell program is automatically loaded to give the user an operating environment in which to enter commands.

Linux built-in commands and external commands

bash is a shell program used by default in many Linux systems, with files located in /bin/bash

    • Internal Command : Refers to special instructions that are integrated into the Shell interpreter program (such as bash) and become built-in (built-in) directives. Internal commands are part of the shell, so there is no separate system file, and as long as the shell interpreter is running, internal instructions are automatically loaded into memory and reside in the system memory, which the user can use directly. Internal commands do not need to re-read files from the hard disk, and parsing the internal command shell does not require creating child processes, so execution is more efficient. Common BUILTIN commands are: CD, echo, history, etc.

    1. Some commands are built for their necessity, such as a CD used to change the directory, and read will pass the input data from the user (and file) to the shell for external light.

    2. Another built-in command exists for efficiency, the most typical of which is the test command, which is often used when scripting. There are also I/O commands, such as echo in printf.

    • Shell function : The Shell function is a well-functioning set of program code written in the shell language that can be referenced like a command.

    • external command : Refers to a script file or binary program on a Linux system that is capable of accomplishing certain functions, each of which corresponds to a file in the system and is a command other than the Shell interpreter program, so called an external command. The Linux system must know the file location of the external command before it can be loaded and executed by the shell.

The external command is the command executed by the shell copy (the new process), and the basic process is as follows:
A. The shell creates a new process through fork () . This process is a copy of the shell.
B. In the new process, look for specific commands within the directory listed in the PATH variable.
/bin:/usr/bin:/usr/x11r6/bin:/usr/local/bin is a typical default value for the PATH variable.
When the command name contains a slash (/) symbol, the path lookup step is skipped.
C. In the new process, execute the shell process in progress with the new program found using the exec series function.
D. Once the program is complete, the original shell will then read the next command from the terminal and execute the next command in the script.

By default, Linux systems add directories that hold external commands, programs (such as/bin,/usr/bin,/usr/local/bin, and so on) to the user's search path, and users do not need to specify a specific location when using external commands located in those directories. Therefore, in most cases, there is no need to deliberately distinguish between internal and external commands, the use of the method is basically similar.


use the type to see if it is a built-in command :
Type (without parameters) shows whether the command is built-in or external
-t:file external commands; alias command aliases; Builtin built-in commands
-A: The command path path is displayed

[[Email protected] ~]# type Catcat is/bin/cat[[email protected] ~]# type CDCD is a shell builtin[[email protected] ~]# ty PE Lsls is aliased to ' LS--color=auto '

How to perform interactive commands :
After the user enters a command at the command line, the shell typically fork and exec the command, but the shell's built-in command is the equivalent of invoking a function in the shell process and does not create a new process.
For example: CD, alias, Umask, exit and other commands are built-in commands, usually with the which command can not find the location of the program File command is built-in command, built-in command does not have a separate man manual, to view the built-in command in the man manual, should man Bash-builtins, the built-in command does not create a new process, but it also has the exit status, usually with 0 to indicate that a success nonzero means failure, although the built-in command does not create a new process, but there will be a status code after execution, you can also use the special variable $? read out


Absolute path vs. relative path

As you can tell by the above description, when executing an external command in bash, you need to know the location (path) of the file

    • Absolute path : Starting from/directory. Path from the root directory/start. Absolute path is better than the correct degree, if the writing program (shell scripts) to manage the system under the conditions, be sure to use absolute path notation.

    • relative path : not from/start. The path relative to the current working directory.


Special Directories :

. Represents the current directory

.. Represents a previous level directory

~ Represents the user's home directory

~username Enter the home directory of the specified user

-Represents a previous working directory

Will exist under all directories. And.. Two directories representing this layer and the upper level directory, respectively. But under the root directory, represents the previous layer (.. ) is the same directory as the root directory itself (.).


Shell command Search mechanism

Think of a Question No, why can we execute these commands like LS, cat in any directory without specifying their absolute or relative paths? But no hint: command not found?

Note: In addition, we discuss the premise that when you type a command and do not specify the path of the command, for example, we typed the command is in the form of commandname instead of/path/commandname or./path/commandname. . Once we specify a relative or absolute path to a command (or script or binary), there is no search mechanism.

Typically, when we type commands such as LS at the Linux system terminal prompt, how does the shell find this command? What kinds of commands are there in the shell? How are these commands loaded?
  

first, the Linux command search order :

When we type a command, the shell searches in the order in which the alias->keyword->function,->built-in-> $PATH , on a " first come first served" basis Principle, that is, if a command named myCMD exists in both alias and function, then it will certainly use alias's myCMD command (which, of course, is not absolute, as the following is a special case).


1) Hash command :

First of all, let's look at the hash this command (and what I said above "not absolute" has a relationship!), the hash command is used to record the command path record cache table that the user has typed in the current shell environment, primarily to speed up command search. Let's look at an example:

Example: I type LS, find, pwd, ls, echo "Hello, World" under the shell, mail and if a total of 7 commands (note that LS executes 2 times), the following is the result of history:

1 ls 2 find 3 pwd 4 ls 5 echo "Hello, World" 6 mail 7 if

Well, now I execute the hash command, which shows the result:

[[email protected] var]$ Hash hits command 1/bin/mail 2/bin/ls 1/usr/bin/find

Do you have any idea what you've found? The left column of the hash table indicates that the command was used several times in the current shell environment, and the right column represents the command path. But we find that the hash cache is missing if,pwd and ECHO3 commands, why? We are here to come to an important conclusion is: (1) hash does not record function, built-in command (in fact, including alias), why? The answer is that they do not have a path, that is, they do not exist under a directory, they are loaded with the shell and then exist in memory, so is it necessary for such a command to be cached to improve search efficiency?!

But some people will say, LS not a hash recorded it? Yes, your observation is very detailed, usually LS in bash is an alias, then, here we first concluded: (2) alias in the definition of the path is included in the alias command will not be recorded in the hash, only the non-specified path alias will be recorded in the hash. Case Examples:

This is the definition of the LS alias in my current shell (bash) environment

[[email protected] var]$ alias Lsalias ls= ' Ls–color=auto '

(Note: The following "Ls–color=auto" does not specify a path such as/bin/ls)

So, as you can see, I typed the ls command 2 times (the alias of Ls–color=auto), so I could see it recorded in the hash. Here's an example of a write command:

[email protected]//]$ alias Write-bash:alias:write:not found [[email protected]//]$ write usage:write user [t TY] [[email protected]//]$ Hash hits command 1/usr/bin/write 1/bin/mail 2/bin/ls 1/usr/bin/find

Write this command does not have alias, that is, when executing the Write command is actually found in the path variable/usr/bin/write the binary file to execute, when the hash recorded the write path and was quoted 1 times, I then define the write alias to be the write itself, but specify that the specific path is/usr/bin/write:

[[email protected]//]$ alias write= '/usr/bin/write ' [[email protected]//]$ alias write alias write= '/usr/bin/write ' [ [Email protected]//]$ write Usage:write user [TTY] [[email protected]//]$ Hash hits command 1/usr/bin/write 1/BI N/mail 2/bin/ls 1/usr/bin/find

See, the hits number of write in the hash table is still 1 times; It is important to note that when we define the write alias (Specify the path), path will not be searched, why? Very simple, because the write alias has already indicated its specific path!

Then unalias off write to redefine the write alias:

[Email protected]//]$ Unalias write [[email protected]//]$ alias Write-bash:alias:write:not found [email Protec Ted]//]$ alias write= ' write ' [[email protected]//]$ alias write alias Write= ' write ' [[email protected]//]$ write us Age:write user [TTY] [[email protected]//]$ Hash hits command 2/usr/bin/write 1/bin/mail 2/bin/ls 1/usr/bin/fi nd

This time, we did not specify a path in the write alias, and when we have defined the write alias to execute write, the hash table will be hits once. It is important to note that when we define the write alias (not specifying the path, compare to the example above), path will be searched, so the hash hits increased. Please remember that if alias is defined as a path-containing aliases command, it will not be recorded in the hash, only alias without the specified path will be recorded in the hash of this conclusion.

In addition, hash because it is built-in command, so use help hash to see the aid. A common hash-r is used to empty the hash table, and hash-d name is used to delete a command. Such as:

[[email protected]//]$ Hash hits command 3/usr/bin/write 1/bin/mail 2/bin/ls 1/usr/bin/find Delete specific: [[email Pro] tected]//]$ hash-d ls [[email protected]//]$ Hash hits command 3/usr/bin/write 1/bin/mail 1/usr/bin/find empty H Ash: [[email protected]//]$ hash-r [[email protected]//]$ hash hash:hash table Empty

2) Set +-h:
  
Set command everyone should be very familiar with, what we are mainly talking about here is the function of Set +-h: Help set can see "H Remember the location of commands as they is looked up." Chinese means memory command. path for easy querying. When we type set +h and then run the hash:
  
[[Email protected]//]$ set +h
[[email protected]//]$ hash
-bash:hash:hashing disabled
 
This means "set +h" is used to disable hashing and "set-h" is used to enable hashing.

 

Summary: We all know that the order of the shell in the search command is alias->keyword->function,->built-in-> $PATH, then there are 2 points to note is (1) Hash does not record function, built-in command (in fact, also include Alias), (2) alias if the definition of the path is included in the alias command will not be recorded in the hash, only the alias without the specified path will be recorded in the hash. Also, (3) Do not forget that we are discussing the premise that a is restricted to the specific shell type B) and is only valid in the current shell environment. REMEMBER!!!

Here, let's consider a question:

Take a look at the following implementation:

[[Email protected] var]$ function gcc {echo "Just a test for GCC";}
[[email protected] var]$ alias gcc= ' gcc '

[Email protected] var]$ gcc
Just a test for GCC

[Email protected] var]$/USR/BIN/GCC
Gcc:no input Files

[[email protected] var]$ alias gcc= '/USR/BIN/GCC '
[Email protected] var]$ gcc
Gcc:no input Files

[Email protected] var]$

Why does GCC have a different response when defining GCC's funtion and specifying that the specific/USR/BIN/GCC path is not specified when the two-time alias is defined? According to Alias->keyword->function,->built-in-> $PATH this order, should execute the alias of GCC ah?! Please think!
Of course, don't worry, I'll give you an answer later. But, please think about it!

Four, the command example:

* Alias (alias):
The alias command is usually set in Files ~/.BASHRC and/ETC/BASHRC, ~/.BASHRC is typically used for the user's own environment, and/ETC/BASHRC is used for global definition (i.e., for all users, of course, only for the user shell is bash). The specifics of these two file relationships and how they are loaded are described later.

* Shell keyword (shell keyword):
such as if,while,until,case,for these commands.

* Function (Functions):
  
Example:
  
Defines a function called PWD, whose function is to simply display the phrase "my function pwd"
function pwd {echo "my function pwd";}
After you have defined it, you can use set or type-a pwd to view it and cancel it with unset pwd.

* Shell built-in command (shell built-in commands):
command enable to view the built-in commands in all current shell environments; Or use the man CD (any one of the built-in commands) to see the top of the manpage lists all the built-in commands.

* PATH Variable
The variable is defined in file/etc/profile,/etc/profile.d/*.sh (POSIX), ~/.bash_profile (bash).

The order of loading is:/etc/profile First (invoke/etc/profile.d/*.sh), then ~/.bash_profile, then ~/.BASHRC by ~/.bash_profile and then by ~/. BASHRC go to invoke execution ~/.BASHRC, ~/.BASHRC then call execute file/ETC/BASHRC.
  
1) in order to see the specific loading order, you can add two sentences to the head and tail of the four files, for example:

[email protected] ~]$ cat ~/.BASHRC
echo "Start of ~/.BASHRC"
if [-F/ETC/BASHRC]; Then
. /etc/bashrc
Fi
Alias Ll= ' Ls-l '
Alias cp= ' Cp-i '
Alias mv= ' Mv-i '
Alias rm= ' Rm-i '
......

echo "End of ~/.BASHRC"
Other files, so that when you log into the system with a user, you will see the following display, such as:
Start Of/etc/profile
End Of/etc/profile
Start of ~/.bash_profile
Start of ~/.BASHRC
Start OF/ETC/BASHRC
End OF/ETC/BASHRC
End of ~/.BASHRC
End of ~/.bash_profile

From the above show you can clearly see the loading order of each file and invoke the execution relationship with each other (note view start and end).

2) The relationship between the path variable and the hash
Here, let's look at an example:

[Email protected] ~]$ echo $PATH
/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin:/home/ancharn/bin
 
I first write a script named test.sh in the/home/ancharn/bin directory, which reads as follows:
[Email protected] bin]$ cat/home/ancharn/bin/test.sh
  
#!/bin/sh
# Just test for PATH and hash
echo "This is my 1st Shell script In/home/ancharn/bin directory."

# End
  
[Email protected] bin]$
Then, execute the test.sh script as follows:
[Email protected]/]$ echo $PATH
/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin:/home/ancharn/bin
[Email protected]/]$ test.sh
This is my 1st Shell script In/home/ancharn/bin directory.
[[email protected]/]$ hash
Hits command
1/home/ancharn/bin/test.sh
Next, create a file with the test.sh name in the/usr/bin directory, with the following contents:

[Email protected]/]$ cat/usr/bin/test.sh
#!/bin/sh
# Just test for PATH and hash
echo "This is my 2nd Shell script In/usr/bin directory."

# End
Continue executing the test.sh script:

[Email protected]/]$ test.sh
This is my 1st Shell script In/home/ancharn/bin directory.
[[email protected]/]$ hash
Hits command
2/home/ancharn/bin/test.sh
 
What does it mean?

If you follow path in the order of/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin:/home/ancharn/bin, you will find/usr/bin and then find/home/ancharn/bin, Note that this premise is that there is no record of the command in the hash table, so we see that the/usr/bin/test.sh script was not executed because the shell went to the hash table to see the cache before executing test.sh, and then proceeded to execute the/home/ancharn/bin /test.sh script, so we see the hits number increased once, and/usr/bin/test.sh will not be executed.

Now, we empty the hash and re-execute the test.sh script:
  
[Email protected]/]$ Hash-r
[[email protected]/]$ hash
Hash:hash Table Empty
[Email protected]/]$ test.sh
This is my 2nd Shell script In/usr/bin directory.
[[email protected]/]$ hash
Hits command
1/usr/bin/test.sh

It's normal now. So be sure to pay attention to the relationship between path and hash.

Note: Su, su-, Bash–login, bash–norc the difference between these commands is whether the Login-shell is executed, you can su and Su-after, then run the Echo $PATH to see how different.

Well, to answer the above study questions, its core is that alias if defined as alias gcc= ' GCC ', in fact alias->keyword->function,->built-in-> $PATH This order does not change, But to know that alias gcc= ' gcc ' does not specify a path alias will find the "GCC" after the alias, and then to find the later designated ' GCC ', how to find? The next, of course, is keyword->function ... in this order. And if it is alias gcc= '/USR/BIN/GCC ' the definition of the specific path of the alias, then alias execution will directly find the specific file and skip all subsequent searches (that is, keyword->function,-> Built-in-> $PATH). Please keep an eye out for them.

Finally, when you do the experimental verification can be divided into 2 types of verification, because a command cannot belong to both keyword and built-in, so you can:
  
1) Select a keyword such as while, define a while alias,function, and then write a shell script name for while stored in the path variable at a certain paths;

2) Select a built-in command such as PWD to verify.


This article is from the "Share Your Knowledge" blog, so be sure to keep this source http://skypegnu1.blog.51cto.com/8991766/1620444

Linux Basics: Linux (BASH) command execution and search mechanism

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.