All rights reserved, please indicate the source when citing
Understanding the Linux Command-Line Interface (CLI)
1.0 Introduction to Shell
Logging into the command-line interface
Superuser (root)
Linux command syntax
Control keys in the CLI
<Ctrl+Alt+F(1~7)> Switching terminals
<↑>, <↓> History search
Reviewing command history with the "history" command
<!> Specifying command numbe
<Ctrl+C> Stopping current operation
<Ctrl+D> Logging out or ending a file
<Tab> Autocompletion
<Ctrl+R> History search + autocompletion
Input Control
<Ctrl+U> Deleting the entire line
<Ctrl+W> Deleting input before the cursor
<Ctrl+K> Deleting input after the cursorr
<Ctrl+L> Clearing the screen above the cursor
1.1 Logging out
logout: Log out
exit: Exit the current shell
su: Temporarily change user
1.2 Shutdown
poweroff : Shut down
halt : Shut down
reboot : Restart
shutdown : Shut down
sync : Synchronize buffer memory and hard disk
runlevel : Check the current run leve
init : Execute run level
1.3 Clearing the screen
clear : Clear the screen
reset : Reset the screen
1.4 Auxiliary documentation
man : Command manuall
info : Command manuall
--help : Command's built-in help
ENG⇒中ENG⇒中
1.0 Introduction to Shell
The text interface under UNIX/Linux is called "Shell". The figure below shows that the operation of the text interface ( Command - Line Interface , CLI) is communicated and executed through the Shell and the kernel (Kernel). So what is Shell? "Shell" means "outer shell" in English. I personally think that using shell has vividly explained the text operation interface of Linux.

Before further explaining Shell, tell a story: < Zhuangzi >(莊子) records a wonderful dialogue:
Dongguozi(東郭子) asked Zhuangz(莊子) : What is the Tao(道)? Where is it located?
Zhuangzi replied: It is everywhere.
Dongguozi asked: Can you give an example?
Zhuangzi answered: It is in the body of a small ant.
Dongguozi questioned: The Tao is in such a lowly place?
Zhuangzi responded: It is also in the weeds.
Dongguozi inquired: Why does it become even lower?
Zhuangzi explained: It is in the shards of a broken pot.
Dongguozi asked: Why does it keep deteriorating?
Zhuangzi replied: It is in dung and urine!!!
Dongguozi exclaimed: What the..FxxK. ~!@87#$%^&*..e04!..
This is the famous story of "Tao in Dung and Urine"(道在屎溺 ) from <Zhuangzi>, but what does it have to do with Linux? Well, once Linux starts running, the Linux kernel operates within the PC, and the concept of "Tao in Dung and Urine" becomes ubiquitous. Although the Linux kernel runs throughout the world, we can't directly interact with the kernel; we can only communicate with it through the shell. Even though the manipulation through the textual interface only touches the "shell" of the kernel and doesn't directly access its core ("明心見性"), its power is already formidable.
In a broader sense, a graphical user interface (GUI) or the currently popular touch panel can also be considered as a type of shell. Regardless of the shell used to communicate with the kernel, there are limitations and blind spots. For example, if my native language is Taiwanese, when I think about certain things, I may think in Mandarin or Taiwanese. Additionally, because I have some knowledge of the C programming language, I occasionally think about things using C language (such as how to write this question in C).
Indeed, thinking solely in language can have limitations as it is bound by the expressiveness of the language itself. imagine how deaf-mute people think about things without language? Maybe they are all images? What about deaf and blind people? How to think about things? I don't know, but at least it shows that you can think about things without language or images.
One significant difference between humans and computers is that computers can be reinstalled with different operating systems or software applications, allowing for changes in their capabilities and functionalities. On the other hand, once humans acquire knowledge and form biases, it becomes challenging to "emptiness" their existing ideologies. Once we learn to think using language or imagery, it is difficult to revert to a state of thought without language or imagery. Perhaps, thinking through language or imagery can sometimes limit us by the expressive capabilities of those mediums, "Directly pointing to the human mind, clearly seeing the nature of the mind." (直指人心,明心見性), as there are many aspects of life that cannot be fully described or captured through words or images.
For an operating system, thinking in terms of images is a graphical user interface (GUI), and thinking in terms of language is a text-based user interface (CLI). There is also no solution within a solution, because ordinary people cannot directly operate the Kernel directly.
UNIX/Linux leans towards a text-based operating interface (CLI) that relies more on language for thinking. For people accustomed to the graphical user interface of Windows, their initial encounter with a text-based interface can often be restricted by preconceived notions and ideologies, causing a sense of dissonance. It is recommended to "emptiness"(放空) previous learning and create a "vacuum of wondrous existence"(真空妙有) by clearing existing biases. Only by creating this empty space can new content be accommodated.
Shell is a textual language and it is an interpreter language used for Kernel. The general programs on a computer, for the sake of execution speed and confidentiality, are developed using high-level programming languages. These high-level languages are then compiled into machine code, which the computer can execute, using a compiler.
On the other hand, an interpreter language, like Shell, does not translate the entire program at once. Instead, it interprets and executes one line of instructions at a time, communicating with the relevant application software or the core of the operating system. So, when a user enters commands in a text interface, they are translated by the Shell interpreter and executed by the Linux kernel, one line at a time.
Scripting languages, are a collection of commands in a text interface that work together to accomplish a specific action. Some common interpreter languages for PCs include Shell, Python, JavaScript, and HTML.
Interpreted languages have their advantages and disadvantages. Here are some of them:
- Advantages:
- Easy to read and learn:
Software written in high-level languages needs to be compiled into machine code that the computer can execute in order to be validated. If there are bugs, the original source code needs to be modified and then recompiled into machine code for validation. On the other hand, interpreted languages can be executed without going through a compiler, making them relatively easier to learn and read.
- Good interactivity:
Because only one line is executed at a time, it is easier to interact with commands.
- Easy cross-platform:
As long as the operating system or application can interpret the interpreted language, it can be cross-platform. For example, if a web page is written in HTML, as long as the application can interpret HTML language, it can be accessed across different platforms. Whether the user is using a mobile phone, PC, or iPad, and regardless of whether they are using Edge/Firefox/Chrome or other browsers, they will get similar results when browsing the same web page. Additionally, UNIX/Linux follows an important design philosophy of "Choose portability over efficiency." Therefore, it strongly recommends using Shell Script as much as possible to complete programs.
- Disadvantages :
- Slower execution speed::
Interpreted languages generally have slower execution speeds compared to compiled languages since the code is translated and executed line by line.
- Code protection:
Interpreted languages make it easier for others to read and modify the source code, as it is typically distributed in its original form. This can be a concern for proprietary or sensitive applications.
When a Linux user logs into the text-based interface, they are effectively using an interpreted language of a specific shell to communicate with the Linux kernel. Commonly used shell interpreter languages in Linux include Bourne shell (bash), C shell (tcs), Kom shell (ksh), zsh, among others. Each shell has slightly different syntax. The majority of Linux distributions default to the Bourne-Again shell (bash) as the default shell. If a user is unsure which shell they are currently using, they can enter the command echo $SHELL to check the currently active shell.
The king of text operation interface is UNIX/Linux. If the user is not familiar with and uses UNIX/Linux text operation interface, he can first experience the text operation interface under Windows. For example, if you want to find out how many files named "readme" are in the hard disk, you can open the "Execute" dialog box by pressing the Windows logo key + R in Windows, and enter cmd into the "Command Prompt" Enter dir c:\readme* /s/b/a to have a look, the output is below (it turns out that my hard disk has so many files named "readme".)
Example
:Windows Command Prompt Enter dir c:\readme* /s/b/a
C:\Documents and Settings\User>dir c:\readme* /s/b/a ←Enter the blue text portion and press <Enter>
c:\android-sdk-windows\tools\Jet\demo_content\README.txt
c:\android-sdk-windows\tools\Jet\JetCreator\ReadMe1st.txt
c:\android-sdk-windows\tools\Jet\logic_templates\README.txt
c:\BC45\README
c:\cygwin\etc\alternatives\README
c:\cygwin\etc\openldap\schema\README
(The following is omitted) |
Continuing from the previous example, if you want to delete all the "readme" files in the hard disk, just enter del C:\readme* /f/s/a . The above two examples can be operated with a graphical interface It must be very hard, is the text operation interface more powerful than you imagined? And the text operation interface under Windows or DOS is nothing compared to Linux/Unux.
Logging into the command-line interface
Currently mainstream Linux distributions, after booting, there should be a login screen similar to the "graphical operation interface" (GUI) as shown below. After logging in, it is similar to operating Windows, although the GUI does have its convenience. But the real power of Linux is the "Command Line Interface" (CLI),
But how to log in to the CLI? It turns out that Linux is originally a "multi-person and multi-tasking" operating system. It is set that 7 users can log in at the same time (different Linux distributions may be slightly different), and the login of the graphical operation interface is only one of them.
Press Ctrl + Alt + F1 ~ Ctrl + Alt + F7 at the same time to freely switch between different terminals (terminal), for example, press Ctrl + Alt + F1 for terminal tty1, press Ctrl + Alt + F2 for terminal tty2 ... Press Ctrl + Alt + F7 It is tty7, most of the Linux distributions, terminals tty1~tty6 are text operation interface, and tty7 is graphic operation interface. (Different Linux distributions are slightly different.)
Taking Fedora 8 as an example, after booting, the graphical operation interface shown above is tty7, press Ctrl + Alt + F1 ~ Ctrl + Alt + F6 , and the text operation interface as shown below should appear Login screen:
The login screen of the text interface
Fedora
release 8 (Werewolf) ←Display the information of the Linux distribution
Kernel 2.6.23.1-42.cf8 on an i686 ←Display the Linux Kernel version
localhost login: aaa↵ Enter ←Enter the user account (in this example For the account "aaa" created when creating a user account
password:(enter the user's account password)↵ Enter For security reasons, there will be no message on the screen when entering the account password
[aaa@localhost ~]$ ← The prompt after login, if the shell type is "bash", generally it is "[account@hostname+directory location]" |
When logging in with a certain account, you can press Ctrl + Alt + F1 ~ Ctrl + Alt + F7 to log in to other ttys with other identities.
Since different Linux distributions or Unix preset shells are not the same, for example, BSD-like usually uses csh (C shell), and most Linux uses bash (Bourne-Again shell). The common ones are ksh (Kom shell), Z shell (Zsch), etc. Each shell operation is slightly different, but don’t worry too much if the preset shell is not familiar to you, most Linux distributions will provide a variety of commonly used shells Users can change the Shell by themselves. For example:
$ echo $SHELL ↵ Enter ←Display the currently used shell
/bin/bash
$ chsh -l ↵ Enter ←Query which shells are available
/bin/sh
/bin/bash
/sbin/nologin
/bin/zsh
$ chsh -s /bin/zsh ↵ Enter ←designate "Z Shell" as the default shell for this account (you need to log out and then log in to take effect) |
The login prompt usually includes information such as the username, hostname, and current directory, which helps identify the user's location within the file system. It often takes the form of:
[username@hostname:current_directory]$ |
Here's a breakdown of the components:
(1) username: The name of the user who logged in.
(2) hostname: The name of the machine or system the user is logged into.
(3) current_directory: The current working directory where the user is located.
(4) $: the symbol at the end, which is usually "$", will change to "#" to indicate to the operator that they are logged in as the root
.
- Superuser (root)
Because Linux is a multi-tasking operating system, each file or command has permissions to regulate. For example, others cannot peek at my files without authorization, and I cannot delete or modify other people's files or operate certain commands without authorization. The only exception is to log in with the "root" account; the "root" account is also called "superuser" or "system administrator" or "super user".
Logging in as the "root" account in Linux grants unrestricted access, almost without any restrictions. However, with great power comes great responsibility, and it is a double-edged sword. Improper operations can potentially damage the entire system. Therefore, unless necessary, such as for maintenance or administration purposes, it is advisable not to log in as the "root" account. It is recommended to perform routine operations using a regular user account. The more rules and regulations followed, the more secure the system tends to be..
In Fedora, the default text-based login prompt is displayed as "[username@hostname+current_directory]$". If you log in with the "root" account, the symbol at the end, which is usually "$", will change to "#" to indicate to the operator that they are logged in as the root user.
Linux command syntax
When explaining the Linux command syntax, some Linux commands will be used as examples. If the user does not understand the purpose and usage of the Linux commands in the examples, it is recommended to experience the examples first.
Basically, the basic syntax of Linux is as follows:
[\]COMMAND [-OPTIONS] [-- SUB-OPTIONS] [PARAMETER] [\↵ Enter] [;] ↵ Enter
Where "[ ]" is an option, which is not necessary, Each element of the instruction syntax is described as follows:
- "\" :Remove alias
Entering the escape character "\" before the command means "removing aliases"; for example, most Linux distributions make the files with different attributes display different colors in order to make it easy for users to understand at a glance when issuing the ls command. In fact, it is to execute ls --color=tty means that ls --color=tty is the alias of ls , but if you think it is unnecessary, enter "\" (such as \ls ) before the command to remove the alias. example:
Example:
$ ls ↵ Enter ←The Fedora 8 command "ls" actually executes "ls --color=tty", so the output files with different attributes will display different colors
bin
dev home lost+found misc net
proc sbin srv tmp var
boot etc lib media mnt
otp root selinux sys
usr
$ \ls ↵ Enter ← input "\" before the command means "remove alias", the output will not be colorful
bin dev home lost+found misc net
proc sbin srv tmp
var
boot etc lib media mnt
otp root selinux sys
usr
|
- "COMMAND" :Commands and instructions .
The command is a necessary part, and the difference from the DOS command is that the upper and lower case have different meanings, and the Linux command can be built in the shell (such as cd, echo, etc.) or can be an executable file (such as /bin/ ls , /bin/mv, etc.) or an alias , if it is an executable file, its location is in its environment variable "PATH" and you don't need to enter the path of the command (you can enter echo $PATH to query the path).
The order of executing the command is to find the alias first, then find the shell built-in if it cannot be found, and then find the executable file if it cannot be found again.
Example:
$ type -a pwd ← Check that the command "pwd" is a shell built-in or executable file or alias
pwd is a shell builtin ← There are two commands "pwd", one is the shell built-in, and the other executes File "/bin/pwd
pwd is /bin/pwd
$ cd /var/mail↵ Enter ← Enter directory "/var/mail"
$ pwd↵ Enter ←Execute the built-in "pwd" command in the shell (built-in takes precedence)
/var/mail← Built-in command "pwd" displays the link file
$ /bin/pwd↵ Enter ← Change the executable file "/bin/pwd "See if the output is different from the built-in
/var/spool/mail ← Executive file command "/bin/pwd" shows the real path |
- "-" :The symbol of the option.
There is at least one space between the command and the option symbol "-", and the option character is directly connected to the "-" without a space, and multiple options "-" can be combined.
For example:
- ls -a: There is at least one space or more between the command ls and the symbol "-" of the option, so ls -a and ls -a are the same and ls-a is wrong syntax (no spaces), and ls - a is also Incorrect syntax (because of a space after "-").
- Multiple options "-" can be merged into ls -alR , of course, as long as you are happy, you can also partially merge them such as ls -al -R .
- ls -L≠ ls -l because the case sensitivity of the command and option characters has different meanings.
Spaces can also be used for the options of a few commands, such as ps aux , but there are only a few commands in this process.
- "--" :Sub-options
Some commands also have sub-options "--", such as mv --help or ls --color=no .
- "PARAMETER" :Parameter or also known as argument.
Parameters can be files or variables or paths or combinations thereof or other symbols such as stat -c%F%i /etc/fstab or more + 30 /etc/prelink.conf or shutdown -r +3 .
- 〝\〞↵ Enter : Escape Character
If a command is too long or for other requirements, the escape character "\" + ↵ Enter can be used. Then, on the next line, you can continue entering the unfinished part. In a CLI the "\ ↵ Enter" sequence will be treated as invisible or ignored.
Example:
$ cat /etc/fst\↵ Enter ←Enter the blue text + <Enter>
> ab↵ Enter ←When entering the blue text, the ">" symbol is automatically generated and does not need to be entered.
LABEL=/
/
ext3
defaults 1 1
LABEL=/boot
/boot
ext3
defaults 1 2
tmpfs
/dev/shm
tmpfs defaults 0 0
devpts
/dev/pts
devpts gid=5,mode=620 0 0
sysfs
/sys
sysfs defaults 0 0
proc
/proc
proc
defaults 0 0
LABEL=SWAP-sda3
swap
swap
defaults 0 0
$ cat /etc/fstab↵ Enter ←This example is the same as the previous one, but the previous example used "\ <Enter>" to input it in two lines.
LABEL=/
/
ext3
defaults 1 1
LABEL=/boot
/boot
ext3
defaults 1 2
(The rest is omitted.) |
- ";" :command terminator
The semicolon can be used to execute multiple commands on a single line. For example:
Example:
$ clear;cd /;ls↵ Enter ←When there are multiple commands, you can use the ";" to separate one command from another
bin dev home lib media mnt opt root selinux sys usr
boot etc lib lost+found misc net proc sbin srv tmp var
|
- ↵ Enter :Command input is complete
The command will be accepted only
after pressing ↵ Enter command.
Control keys in the CLI
In the text interface, many useful control keys are preset, and the operation may be slightly different in different shells or versions; the introduction in the following example is based on the default "Bourne Shell" (bash), and the commonly used combinations are as follows :
- <Ctrl+Alt+F(1~7)> Switching terminals
Most of the Linux distributions, you can press Ctrl+Alt+F1 ~ Ctrl+Alt+F7 to switch between different terminals tty#, Fedora 8 defaults tty1~tty6 as Text operation interface and tty7 is a graphics operation interface (different versions may be different).
- <↑>, <↓> History search
After the input string + ↵ Enter, most Linux distributions will record this string, and you can use ↑、↓ keys to query the previously input string.。[Note]
- Reviewing command history with the "history" command
As mentioned above↑,↓are used to call out the string (command) that has been input, but how do we know what command will appear when we press↑ or ↓ ? Just enter history to know.
Example:
$ history↵ Enter
The following are the strings (commands) that have been entered after entering the "history" command.
1 cat proc/cpuinfo
2 ls
3 rm ex07-7.cpp |
In the above example, the leftmost number is the "command number", and the right number is the command. If there are too many history records, sometimes the command you want to find will be lost. You can use history -c to clear it.
- <!> Specifying command number
If the command number is far from the command I want, won't I have to press ↑ or ↓ endlessly? In this case, using "!" for referencing and searching is very convenient. The usage of ! is as follows.
- ! !:
Enter two consecutive〝!!〞o repeat the last instruction.
- ! #:
(# is a number) the command to specify the command number; for example, input!80 to specify the command with the command number = 80.
- ! -#:
(# is a number) specifies the command counting from the last command, counting down to the # command; for example !-3 。
- <Ctrl+C> Stopping current operation
If the operation process is too long or other reasons to give up the current operation, you can use the job control Ctrl + C to stop the current operation.
Example:
$ seq 1 10000000↵ Enter
1
2
3
4
8Ctrol+C ←press <Ctrl+C> to give up the current operation
|
- <Ctrl+D> Logging out or ending a file
Ctrl+D in the text interface has two functions:
- Log out the current user:
In the login prompt of the text interface, when the cursor is at the leftmost position, press Ctrl + D to log out the current user. (Press Ctrl + Alt + Backspace in the GUI to log out the user.)
Example:
$ _Ctrl+D ← Press <Ctrl+D> at this time, it is invalid because the cursor is not at the leftmost position
$ ls_Ctrl+D ← Press <Ctrl+D> at this time Invalid, the reason is the same as above
$ _Ctrl+D ← Press <Ctrl+D> at this time to establish, because the cursor is at the leftmost position, the current user will be logged out |
- End input:
In some CLI, press Ctrl + D to represent End of File (EOF).
Example:
$ cat > EOF-test↵ Enter
Hello, this is a EOF test↵ Enter
Ctrl+D ← press <Ctrl+D> at this time to end input
[aaa@localhost ~]$ cat EOF-test ←verify Look at the newly created file
Hello, this is a EOF test |
- <Tab> Autocompletion
In the text interface, I personally find the "Tab completion" feature using the Tab key to be the most useful. Tab completion significantly reduces the chance of typing errors and saves typing time. It applies to both "Command-Line Completion" and "Filename Completion."
- Command-Line Completion:
When you press Tab in the text interface, it examines the characters already entered to determine the possible commands the user might enter next. If there are multiple possibilities, pressing Tab again will display a list of all the matching commands
Example:
$ lsTab ⇌ Tab ⇌ ←Input "ls" and press <Tab> If there is no response, it means that there are many possibilities, press <Tab> again and all matching commands will be listed
|
- Filename Completion:
After the command input is completed, space more than one space , enter some characters and press Tab , at this time, it will help the user to enter the matching file name according to the space between the characters that have been entered. If there are multiple files that match, click again Tab lists all matching file names. .
Example:
$ ls /etc/hosts.aTab ⇌llow _ ←Enter the blue text,automatically completes filenames when you press <Tab>
|
- <Ctrl+R> History search + autocompletion
Ctrl+R CLI Ctrl+R is a combination of "history search" and "auto-completion." It only auto-completes commands that have been previously entered. Explaining it in detail would take some time, so I encourage you to experience it yourself.
- Input control
When inputting commands, it is inevitable to make typos. Some input control keys can be used properly to reduce the time for correction:
- <Ctrl+U> Deleting the entire line
Example:
$ LS /ETC Ctrl+U ←At any time, pressing <Ctrl+u> before entering
will delete the entire line
|
- <Ctrl+W> Deleting input before the cursor
Example:
$ 0123456789 Ctrl+W ← Input before the cursor will be deleted
|
- <Ctrl+K> Deleting input after the cursorr
Example:
$ 0123456789 Ctrl+K ← Input after the cursor will be deleted
|
- <Ctrl+L> Clearing the screen above the cursor
Pressing Ctrl+L in text mode will clear any content above the cursor.
Example:
$ ls /
bin dev home lost+found misc net
proc sbin srv tmp
var
boot etc lib media mnt
otp root selinux sys
usr
$ history Ctrl+L ← the screen above the cursor will be cleared
|
^ back on top ^
1.1 Logging out
After the user logs in, to change the user, they can enter logout to log out and then log in with another account. In the "general case," entering exit can also log out. So, what is the difference between these two?
logout : Log out
The command to logout the current user's account is log out . After logging out, you can change another account and log in again.
exit : Exit the current shell
Many books say that exit = logout is also a log out, which is actually not correct. The correct point of exit is "exit the current shell ", because most of the users only use one shell, "exit the current shell" is equal to "logout", but if there is a "sub-shell", it is not valid.
For example, the current login is the default shell (called "parent shell"), but in order to have the functions of a certain shell or to execute a script file written by a certain shell, it is necessary to load other shells (called "child shell" or "sub shell")). Entering exit in the children shell is to return to the parent shell, not to log out. After returning to the parent shell, you can log out with either logout / exit
Example:
[aaa@localhost ~]$ echo $SHELL ←query the current shell (parent shell)
/bin/bash ←Currently Bourne shell (bash)
[aaa@localhost ~]$ chsh -l ←query which shells are available ("chsh -l" actually reads the content of the file "/etc/shells")
/bin/sh
/bin/bash
/sbin/nologin
/bin/zsh
[aaa@localhost ~]$ zsh ←Enter available shells (except nologin)
[aaa@localhost]~% ←The prompt symbol has changed, indicating that it has entered another subshell (zsh)
[aaa@localhost]~% logout ←Logout with logout to see
logout: not login shell ←Response zsh is not a login shell So you are not allowed to log out
[aaa@localhost]~% exit ←Exit the current shell
[aaa@localhost ~]$ ←The prompt symbol changes, and returns to the login symbol of the parent shell
[aaa@localhost]~% logout ←At this point, you can use logout to log out
|
su : Temporarily change user
If the user only wants to temporarily use another account for other tasks without the hassle of logging out/logging in, they can use su to temporarily change the user. Then, they can use logout or exit to log out and restore the original login. The usage and explanation of 'su' are as follows:"
Syntax::su [-otpiton][--option][account if no account is specified, the default account is "root")] |
Command name/function/command user |
option |
function |
su/
(Super User) temporarily change user/
Any |
-c command or -command |
Restore the original login after executing the command |
-- or -l or --login ['account number] |
Changing a user also changes the context of that user's work |
If the su command is entered without specifying a username, the default account is 'root.' Another potential source of confusion is the options '- ' or '-l' (lowercase 'L,' but it can be omitted and written as su -). The difference is that when using '- ' or '-l,' it changes the working environment (including the working directory) to that of the specified user.
Example: (first log in with a non-"root" account, then use su and su - to change to a "root" account)
[aaa@localhost ~]$ ← Login with a non-root account (the default prompt symbol is "[account@host name + directory location]$")
[aaa@localhost ~]$ su root ←Change the account to "root" , note that there is no "-" option this time (the working environment will not be changed)
Password: ←Enter the root password
[root@localhost aaa]# ← the prompt has changed. However, the working environment has not been modified, and the working directory remains the same as the original user's home directory, which is 'aaa'
[root@localhost ~]# exit ←Restore the original login
[aaa@localhost ~]$ su - ←No account specified, the default account is "root" (this time there is a "-" option)
Password: ←Enter the root password
[root@localhost ~]# ←The current login user has changed to root, and the working directory is in root’s home directory
[root@localhost ~]# exit ←Restore the original login
|
Example:
[aaa@localhost ~]$ su -c 'ls -a' - l bbb ←Change the user "bbb", execute the command "ls -a"
Password: ←It will ask to enter the password of "bbb"
. .. .bash_history .bash_logout .bash_profile .bashrc
[aaa@localhost ~]# ←Automatically restore the original login after executing the command
|
Furthermore, if you are logged in with the 'root' account and use su to temporarily switch to a regular user, you do not need to enter a password.
For more detailed usage of su, please refer to the provided link.
^ back on top ^
1.2 Shutdown
Linux is a multi-user, multitasking operating system. Shutting it down is not as simple as pulling the plug, as there may be other processes that have not been saved. Even if they have been saved, Linux, for performance reasons, may not have actually stored the files on the hard drive. Instead, they are temporarily held in the 'buffer cache' and are written to the disk when there is available time. Improperly disconnecting the power may result in data loss. Therefore, it is necessary to use the correct shutdown command and procedure. The correct shutdown commands are:
poweroff : Shut down
The command poweroff is to turn off all running processes, save the buffer memory data to the hard disk, and if the host complies with ACPI (Advanced Configuration and Power Interface, advanced configuration and power interface), it will turn off the power of the PC by the way.
halt : Shut down
halt is a traditional Unix shutdown command that has the same function as poweroff but does not automatically cut off the PC power supply. halt means that after closing all software programs, you must manually press the switch of the PC to turn off the power suppl
Example:
$ halt
Broadcast message from root (tty1)(Mon jul 4 15:50:44 2011):
The system is going down for system halt NOW!
INIT: Sending processes the TERM signal
[ OK ]
Shutting down Avahi deamon:
[
OK ]
Stopping HAL deamon:
[ OK ]
(...omitted)
Turning off swap:
[ OK ]
Turning off quotas:
[ OK ]
Unmounting file systems:
[ OK ]
Halting system...
System halted. ← Shutdown completed. You can now press the power switch on the PC to turn off the power. |
reboot : Restart
Same as poweroff , but the reboot command will restart the computer.
shutdown: Shut down
"In traditional UNIX systems, since there are usually multiple users logged in at any given time, regular users are not allowed to issue shutdown commands. Only authorized accounts or system administrators can use the 'shutdown' command to initiate a system shutdown.
Here is the usage of the shutdown command:
Syntax: shutdown [-otpiton][time (hh:mm) or (+m) or (now)]['message'] |
command name/function/command user |
options |
Function |
shutdown/
shut down/
Superuser |
-F |
Force fsck to check partition when restarting |
-k |
Send a warning message without actually shutting down. |
-h |
Halt the processes after shutdown. |
-r |
Reboot after shutdown |
The options for time can be:
- hh:mm: Unambiguous time notation.
For example, shutdown -h 10:08 means that it will automatically shut down at 10:08.
- +m: Notation for a few minutes later, 'm' is a number.
For example, shutdown -r +5 'The system will reboot after 5 minutes' means reboot after 5 minutes', and send "The system will reboot after 5 minutes" to every logged-in user, and the sign "+" can be omitted , such as shutdown -h 5 means that it will automatically shut down after 5 minutes.
- now: means immediately.
It is equal to +m, but m=0, such as shutdown -h now = shutdown +h +0 means that it will shut down immediately.
In addition, if there is no option related to shutdown or reboot, the shutdown command will not shut down or reboot, but close all running processes and enter "Single user mode" or "maintenance mode" (maintenance purpose), such as shutdown 3 means that after 3 minutes, all running processes will be shut down and then enter maintenance mode.
In addition, if the shutdown time has not yet come, you can press <Ctrl+C> to stop the shutdown if you regret it.
To perform the test, log in as root.
# shutdown -h now ←Shut down immediately
# shutdown -h +3 ←Set it to shut down after 3 minutes
Broadcast message from root (tty1) (wed jul 6 03:28:13 2011):
The system is going DOWN for system halt in 3 minutes! ← All other logged-in users will receive the message indicating that the system will shut down in 3 minutes.
Ctrl+C ←If the machine time has not yet arrived and you want to regret it, you can press <Ctrl+C> to stop the shutdown. Shutdown
Shutdown cancelled.←shutdown command was terminated by <Ctrl+C> |
Example:
# shutdown -h 0 'hello' ←can add other messages to notify other logins
# shutdown -k now 'hello' ← will not really shut down, just notify other users The login
# shutdown -r 10:08 ←10:08 will reboot
|
sync: Synchronize buffer memory and hard disk
For performance reasons, Linux may not immediately write files to the hard disk. Instead, it temporarily stores them in a buffer in memory until it has time to write the buffered data to the disk. However, the problem is that it's uncertain when Linux will have the time to do so. Therefore, it's uncertain whether the data in the buffer has been written to the disk.The purpose of the sync command is to force the data that is temporarily stored in the buffer to be written to the hard disk. Many people are concerned that some files may not be saved before shutting down the system, so they vigorously execute sync before shutting down.
Example:
# sync;sync;sync;shutdown -h 0 |
^ back on top ^
runlevel : Check the current run level
The runlevel command in Linux is used to determine the current runlevel of the system. A runlevel is a specific operating state of the system that determines which services, daemons, and processes are running. Traditionally, the runlevels in Linux are numbered from 0 to 6, with each runlevel having a specific purpose. The meaning of the runlevels can vary slightly between different distributions, but here is a common mapping:
The runlevle definition of Fedora/Red hat/GentOS and other releases is as follows:
runlevel |
mode |
0 |
Halt or system shutdown |
1 |
Single-user mode or system maintenance mode |
2 |
Multi-user mode without networking (console mode) |
3 |
Multi-user mode with networking (console mode, the default for many servers) |
4 |
Not used or custom runlevel |
5 |
Same as runleve 3, but start and operate with a graphical interface |
6 |
Reboot |
How do I know which runlevel Linux is currently in? Log in as the system administrator and enter runlevel to know.
Example: (log in as root to test)
In this example, "N" represents the previous runlevel, and "5" represents the current runlevel. This information can be useful for understanding the current state of the system and determining what services or processes are expected to be running.
It's important to note that with the introduction of systemd, which is a modern initialization and service management system used by several Linux distributions, the concept of runlevels has been replaced by targets. In systemd, you can use the systemctl command to get information about the current system state and manage services.
init: Execute run level
init executes the running level number,After knowing the meaning of runlevel , you can use the command init to execute/switch the runlevel.
Example: (Test with root login)
# init 0 ←Just to show off a bit, the shutdown command using "init 0" (i.e., runlevel = 0 for shutdown)
# init 6 ←equal to 'reboot' command
# init 1 ← enter maintenance mode |
In fact, the related commands for shutting down, such as poweroff, halt, or shutdown, directly invoke (system call) the init command to execute the shutdown process.
Furthermore, the runlevel at startup is recorded in "/etc/inittab." In most mainstream Linux distributions, the default runlevel at startup is often set to the graphical interface (runlevel = 5). If you wish to change it to a text-based interface during startup, you can locate the following line in "/etc/inittab": "/id:5:initdefault:". The number "5" in this line represents the runlevel. By changing it to "3," the system will boot into the Command Line Interface text-based interface. To enter the GUI later, you can enter the startx command.
^ back on top ^
1.3 Clearing the screen
clear : Clear the screen
clear command to clear the screen,Typing too many Linux commands will make the screen crowded and messy. At this time, you can use the command clear to clear the screen and it will be much cleaner.
reset : Reset the screen
In Linux, the reset command is used to reset the screen and terminal settings. Sometimes ASCII control codes (ASCII from 0 to 31 or 127 to 255) are accidentally output to the screen, or a certain program is abnormal, and the output on the screen may become garbled, even if you use clear or press < Ctrl +L > cannot be eliminated, and there is a trick reset command at this time.
Example:
$ cat /sbin/reboot ←Deliberately output an execution file "reboot" on the screen (execution file is machine code) most of which will cause garbled characters
┌┌␋┼┤│.⎽⎺.2 ␋┼␋├┌⎺±.
▒┌ ⎻
os├ sbi┼] $ c┌e▒r ←Even if you use "clear" to clear the screen, there are still garbled characters, so you have to use the "reset" command to reset the screen to eliminate the garbled characters |
^ back on top ^
1.4 Auxiliary documentation
Linux not only has a wide variety of commands, but each command also has numerous options. It's difficult to memorize all of them. Personally, I believe that understanding the principles behind the commands is more important than memorizing them. I don't intentionally memorize commands; instead, I have a general understanding of the available commands and rely on techniques and Linux supplementary documentation for everyday operations.
In terms of techniques, you can make use of the following methods:
- Commands that have been used but have forgotten their names, history can be used to list the commands that have been issued, which should be able to wake up the lost memory.
- If you can't find it in the long history , but you may still remember the first few words of the command name, you can use the Tab Command-line completion function to find it.
- In the Linux Filesystem Hierarchy Standard, it is mentioned that essential utility software may be stored in /bin or /usr/bin, while system administration-related software may be stored in /sbin or /usr/sbin, and so on. Therefore, you can check these directories to see if the desired commands are available.
- If you forget the built-in commands of the shell, you can enter help to list all the built-in commands of the shell, which may bring back some memories.
The Linux supplementary documentation is even more extensive and serves as a comprehensive command reference manual. The most commonly used Linux supplementary documentation includes:
man : Command manual
The command man means " manual", so if you want to check the manual of a certain command, just enter the man command to read the manual page (or man page) of the command. For example, I want to issue the command shutdown and make it shut down after 10 minutes and notify other logins, but I really can't remember the options, and I can't remember them even if I have Alzheimer's, but I "probably" understand that the options seem to have those functions, If you really want to use it and forget it, use man shutdown to check:
Example:
$ man shutdown
SHUTDOWN(8) Linux System Administrator’s Manual SHUTDOWN(8)
NAME
shutdown - bring the system down
SYNOPSIS
/sbin/shutdown [-t sec] [-arkhncfFHP] time [warning-message]
DESCRIPTION
shutdown brings the system down in a secure way. All logged-in users
are notified that the system is going down, and login(1) is blocked.
It is possible to shut the system down immediately or after a specified
(...omitted)
OPTIONS
-a Use /etc/shutdown.allow.
-t sec Tell init(8) to wait sec seconds between sending processes the
warning and the kill signal, before changing to another run-
level.
(...omitted)
SEE ALSO
fsck(8), init(8), halt(8), poweroff(8), reboot(8)
|
After entering the command reference manual of man, the subsequent operations are as follows: (if you are familiar with vi , you should find that the operations of the two are very similar)
- Q or q : Quit the man page。
- H or h : Displays a brief help message of man
- Page Up / Page Down : Turn pages up and down.
- ← / → : Move 8 lines left and right.
- ↑ or k :To scroll up.
- ↓ or j : To scroll down.
- Home / End : Move to the first/last page.
- / STRING: Search down for a string.
- ? STRING : Search upwards for a string.
- ESC after U :
Cancel the highlighting of the search string (press the ESC key first, then press U when "ESC" appears at the bottom left of the man page ).
- n : with / or ?allows you to navigate to the next occurrence of the search term.
- N : with / or ? Allows you to navigate to the previous occurrence of the search term
- m after CHAR: To mark the bookmark of the current page,
press the m key, and "mark" will appear at the bottom left of the man page. At this time, you can press any letter to represent the bookmark name of this page
- ' fter character: Go to the bookmarked page
Press the ' key, "goto mark" will appear at the bottom left of the man page to the bookmarked position, and you can press the letter marked with m to return to the page just marked).
In addition, what does the number that appears on the upper left of the man page in the above example, such as "SHUTDOWN ( 8 )", mean? It turns out that the number represents the "manual section level", and the meaning of the number is as follows:
man section numbers |
illustrate |
1 |
User Commands |
2 |
System Calls |
3 |
C Library Functions |
4 |
Special Files |
5 |
File Formats and Conventions |
6 |
Games and Demos |
7 |
Miscellaneous |
8 |
System Administration Commands |
9 |
Kernel Interface |
So "SHUTDOWN( 8 )" number 8 indicates that the usage found in the current man page is the command of the system administrator.
Then how do we know what "section number" the command we want to check has? Use the man -f command to find out.
Example:
$ man -f shutdown
shutdown (2)
- shut down part of a full-duplex connection
shutdown (3p)
- shut down socket send and receive operations
shutdown
(8) - bring the system down |
The section numbers of shutdown in the above example are 2, 3p, and 8. In the default situation, if no section numbers are specified, the section numbers checked by man are 1 or 8, but if you are a software developer, you can specify section numbers as 2 or 3p if you want to check the shutdown system call, such as man 2 shutdown and/or man 3p shutdown .
Why do section numbers appear "3p" in addition to numbers? What is 3p? It turns out that section numbers may also have "subsection". The meaning of the sub-section level is as follows:
man Subsection |
illustrate |
p |
POSIX |
x |
X Window System |
The subsection "p" is the so-called POSIX, which is the abbreviation of "Portable Operating System Interface". Another level "x" is the X Window System, which is the graphical user interface (GUI) under UNIX/Linux.
man page In which directory are the reference manuals stored? The path can be checked through the command manpath , so if there is a man page description file attached to the command downloaded by yourself, remember to store the man page of the command in the correct location, otherwise the man page I can't find it.
Example:
$ man whereis | col -b > whereis.txt ← save the man page as a text file |
For more detailed usage of man, please enter man yourself.
^ back on top ^
info: Command manual
Traditional UNIX supplementary documentation only have man page format files, but the man page format files are like "apocalypse", obscure and difficult to understand. Therefore, Linux also provides the info command to view info format files. Personally, I think the format files provided by info are more friendly, but the info format files are much less than the man page format files. Not all commands provide info format files . If a command does not provide a file in the info format, info will be output in the format of the man page
Example:
$ info su
file:coreutils.info, Node: su invocation, Next: dir invocation, Up: Modif\
ied command invocation
2.5 'su' : Run a command with substitute user and group ID
(...omitted)
|
(node), press ↵ Enter Enter this topic, and its detailed browsing controls are as follows:
- q : To quit and exit the info command.
- ? : To display a summary of available key commands.
- h : Displays a brief help message of info page
- Tab⇌ : Choose between different topics (nodes).
- ↵ Enter : When the cursor is on the topic, it will enter the description of the topic.
- s : search string.。
- i : Search for topics in the current info page.
- Page Up / Page Down : Turn pages up and down.。
- ← / → / ↑ / ↓ : Tto navigate within the info page and move between different sections.
- b : Move to the very beginning topic.
- e : Move to the last topic.
- n : Move to the next topic.
- p : Move to the previous topic.
--help : Command's built-in help
In most cases, simply forgetting the options available for a Linux command may not necessarily require using the full power of the man or info commands. If I forget the options for a command, my usual approach is to first try the built-in --help option for that command, which often provides a concise overview of the available options:
Example:
[aaa@localhost ~]$ reboot --help
usage: reboot [-n] [-w] [-d] [-f] [-h] [-i]
-n: don't sync before halting the system
-w: only write a wtmp reboot record and exit.
-d: don't write a wtmp record.
-f: force halt/reboot, don't call shutdown.
-h: put harddisks in standby mode.
-i: shut down all network interfaces. |
Generally, if a command has the --help option, the accompanying explanation tends to be concise, clear, and easy to understand. However, it's important to note that not all commands have a --help option available.
^ back on top ^
[Note]
You can enter echo $HISTSIZE to query the number of commands that can be recorded, and the command histroy actually reads the records of the file ".bash_history" or "histfiles" in the home directory after logging in, and then puts these records in Memroy is accumulated, and it is not written until logout, or the command histroy -w is forced to write.