preface

The importance of learning Linux as a programmer goes without saying. Front-end development has less exposure to Linux than back-end development, so it tends to be overlooked. But learning it well is one of the necessary cultivation of programmers.

If this has helped you, go to 👍.

The author used Aliyun ECS (the cheapest kind) CentOS 7.7 64-bit. You can also install a virtual machine on your own computer, and then install CentOS on the virtual machine (this is completely free). As for the installation tutorial, you can go to Google search, there are many related tutorials.

The Linux foundation

The operating system

Operating System, referred to as OS, is a part of software. It is the first layer of software on the basis of hardware and a bridge between hardware and other software.

The operating system controls the operation of other programs, manages system resources, provides the most basic computing functions, such as managing and configuring memory, determining the priority of system resource supply and demand, and provides some basic service programs.

What is a Linux

The difference between the Linux system kernel and the Linux distribution

  • LinuxThe system kernel is defined byLinus TorvaldsResponsible for maintaining system core programs that provide hardware abstraction layer, hard disk and file system control, and multi-tasking capabilities.
  • LinuxA distribution system is what we often call itLinuxThe operating system is made up ofLinuxKernel and various commonly used software collection products.

Conclusion: trueLinuxThe kernel of the system, and we often sayLinuxA distribution is a complete operating system that includes some underlying software.

Linux contrast Windows

  1. Stable and efficient;
  2. Free (or a small fee);
  3. Few loopholes and quick repair;
  4. Multi-task multi-user;
  5. More secure user and file permission policies;
  6. Embedded system suitable for small kernel programs;
  7. It’s relatively resource free.

Linux System Types

  • Red Hat Enterprise editionLinux : RHELIt’s the most widely used in the worldLinuxSystem. It is a highly performance and stable system used (for a fee) in many generation environments.
  • Fedora: A desktop suite of systems released by Red Hat, providing free access to the latest technologies or tools that will be added as they matureRHELSystem, soFedoraHas become aRHELTest version of the system.
  • CentOSBy:RHELSystem recompiled and distributed to users free of chargeLinuxThe system has a wide range of users.
  • Deepin: China release, integration and configuration of excellent open source finished products.
  • Debian: Stability, strong security, to provide free basic support, has a high degree of recognition and utilization abroad.
  • Ubuntu: is a derivative ofDebianOperating system, the new hardware has a strong compatibility.Ubuntu 与 FedoraThey are excellentLinuxDesktop systems, andUbuntuIt can also be used in the server domain.

The terminal connects to ali Cloud server

By performingSSH [email protected]Command, and then enter the server connection password to log in to the remote server. From now on we can operate the remote server from the local computer.

  1. This black panel is the terminal which is the terminalShellCommand line environment.
  2. ssh root@xxxIt’s an order. It has to beShellCan be executed in.

Shell

The word “Shell” refers to the outer layer of the kernel, i.e. the interface through which users interact with the kernel.

  • ShellIs a program that provides an environment for dialogue with the user. This environment has only one command prompt for the user to enter commands from the keyboard, so it is also called the command line environment (command line interfaceFor short,CLI).ShellReceiving the commands entered by the user, sending the commands to the operating system for execution, and returning the results to the user.
  • ShellIs a command interpreter that interprets commands entered by the user. It supports syntax such as variable, condition judgment, loop operation, so users can use itShellCommand to write a variety of small procedures, also known asShellThe script. These scripts all passShellIs executed by interpretation, rather than by compilation.
  • ShellIs a toolbox that provides a variety of gadgets for users to easily use the functionality of the operating system.

The types of the Shell

There are many types of shells, and any program that provides a command-line environment for the user can be considered a Shell.

Historically, the major shells have been:

  • Bourne Shell (SH)
  • Bourne Again shell (bash)
  • C Shell (CSH)
  • TENEX C Shell (TCSH)
  • Korn Shell (KSH)
  • Z Shell (ZSH)
  • Friendly Interactive Shell (FISH)

Bash is by far the most commonly used Shell. The default Shell in MacOS is Bash.

You can run the echo $SHELL command to view the SHELL in use. You can also run cat /etc/shells to view all the Shell types currently installed on the system.

The command

Command line prompt

After entering the command line environment, the user is presented with a prompt for the Shell. Prompts tend to be a string of prefixes that end with a dollar sign, $, after which users can type various commands.

Run a simple command PWD:

[root@iZm5e8dsxce9ufaic7hi3uZ ~]# pwd
/root
Copy the code

Command parsing:

  • Root: indicates the user name.

  • IZm5e8dsxce9ufaic7hi3uZ: indicates the host name.

  • ~ : indicates that the current directory is the home directory. The home directory of the root user is /root and the home directory of the common user is /home.

  • # : indicates the permissions you have (# for root and $for normal users).

  • Run the whoami command to view the current user name.

  • Run the hostname command to view the current hostname.

How to create, switch, and delete a user will be explained in detail in the following user and permission, here to use the root user first to demonstrate.

[Remarks] Root is the super user and has all permissions of the operating system.

The command format

Command parametersCopy the code

The length of parameters

Single parameter: ls-a (A is short for all, which means all.) Multiple parameters: ls-al (displayed in all files + lists) Single long parameter: ls --all Multiple long parameters: ls --reverse --all Mixed long and long parameters: ls -- all-lCopy the code

The parameter value

Short parameter: command -p 10 (for example, SSH [email protected] -p 22) Long parameter: command --paramters=10 (for example, SSH [email protected] --port=22)Copy the code

A shortcut

Before you begin to learn Linux commands, there are a few shortcuts that you must master in advance and that will continue throughout your Linux life.

  • You can use arrow keys ↑ and ↓ to retrieve past entriesLinuxCommand;
  • Only the first few bits of a command or argument can be usedTabKey completion;
  • Ctrl + R: is used to find used commands (historyThe command is used to list all the commands that have been used before!Order numbered (! 2) to execute the history command directly.
  • Ctrl + L: Clears the screen and moves the current line to the top of the page;
  • Ctrl + C: Terminates the command being executed.
  • Ctrl + U: Cut from the cursor position to the beginning of the line;
  • Ctrl + K: Cut from the cursor position to the end of the line;
  • Ctrl + W: Cuts a word to the left of the cursor;
  • Ctrl + Y: pasteCtrl + U | K | YA command to cut;
  • Ctrl + A: The cursor moves to the beginning of the command line.
  • Ctrl + E: The cursor moves to the end of the command line.
  • Ctrl + DClosed:ShellThe session;

Files and Directories

Organization of files

Check the path

pwd

Displays the path of the current directory

which

In Linux, each command corresponds to an executable program. When you enter a command in the terminal and press Enter, the corresponding program is executed. The program corresponding to the “which” command also exists in Linux.

In general a command is an executable program.

Browse and switch directories

ls

Listing files and directories is one of the most common Commands in Linux.

【 Common parameters 】

  • -aShows all files and directories including hidden
  • -lDisplay detailed list
  • -hSuitable for human reading
  • -tSort files by the time of last modification
  • -ifile-displayinginode ( inodeIs the identifier of the file content.

cd

CD is the abbreviation of “change directory”, which means to switch directories.

CD / --> Go to the root directory CD ~ --> Go to the home directory CD.. /home --> Jump to the upper directory CD./home --> Jump to the current directory of the home directory CD /home/lion --> jump to the root directory of the home directory under the lion directory CD --> Do not add any parameters, but also back to the home directoryCopy the code

[Note] Enter CD /ho + one TAB key to automatically complete the path + two TAB keys to list all possible directories.

du

List the size of a directory.

【 Common parameters 】

  • -hSuitable for human reading;
  • -aSimultaneously enumerates the directory file size information;
  • -sOnly the total size is displayed, not the specific information.

Browse and create files

cat

Display all the contents of the file at once, which is better for viewing small files.

cat cloud-init.log
Copy the code

【 Common parameters 】

  • -nDisplay line number.

less

File content is displayed in pages, which is more suitable for viewing large files.

less cloud-init.log
Copy the code

[Quick operation]

  • Spacebar: Advance one page (one screen);
  • bKey: Back one page;
  • Enter: forward one line;
  • yKey: back one line;
  • Up and down: back or forward one line;
  • dKey: forward half a page;
  • uKey: back half a page;
  • qKey: Stop reading files, abortlessCommand;
  • =Key: displays the contents of the current page from line to line in the file and some other details about the contents of the page;
  • hKey: Display help document;
  • /Key: Press to enter the search modenKey to jump to a matching item, pressNKey to jump to the previous matching item, and you can also enter regular expression matches.

head

Displays the first few lines of the file (default is 10)

head cloud-init.log
Copy the code

“Parameters”

  • -nSpecify the number of rowshead cloud-init.log -n 2 

tail

Displays the last few lines of the file (default is 10)

tail cloud-init.log
Copy the code

“Parameters”

  • -nSpecify the number of rowstail cloud-init.log -n 2
  • -fCheck every second to see if the file has been updated-sParameter specifies the intervaltail -f -s 4 xxx.log 

touch

Create a file

touch new_file
Copy the code

mkdir

Create a directory

mkdir new_folder
Copy the code

【 Common parameters 】

  • -pCreate directory structure recursivelymkdir -p one/two/three 

Copy and move files

cp

Copy files and directories

Cp file file_copy --> file is the target file, file_copy is the copy file cp file one --> copy the file to the one directory, Cp file one/file_copy --> Copy the file to the one directory. File name: file_copy cp *. TXT folder -> Copy all TXT files under the current directory to folderCopy the code

【 Common parameters 】

  • -rA recursive copy, often used to copy an entire directory

mv

Move (rename) a file or directory, similar to the cp command.

Mv file one --> Move the file file to the one directory mv new_Folder one --> Move the new_Folder folder to the one directory mv *. TXT folder --> Move all the TXT files under the current directory Move files to folder mv file new_file --> file Rename the file to new_fileCopy the code

Delete and link files

rm

Delete files and directories. Because there is no recycle bin in Linux, it is difficult to recover once deleted. Therefore, exercise caution when performing this operation

Rm new_file --> Delete the new_file file rm f1 f2 f3 --> Delete the f1, f2, and f3 files simultaneouslyCopy the code

【 Common parameters 】

  • -iConfirm with the user whether to delete;
  • -fForcibly delete files;
  • -rDelete folders recursively, known as deleterm -rf 。

ln

Short for Link, which means creating a Link.

To understand what a link is, let’s take a look at how Linux files are stored:

Linux files are stored in three parts: file names, file contents, and permissions. The list of file names is stored separately from the file contents on other hard disks. Each file name is bound to the file contents by the inode identifier.

There are two types of links under Linux: hard links and soft links.

Hard links

To link the two files share the same content, is the same inode, once had a hard link between file 1 and file 2, then modify any file, change is the same piece of content, its disadvantage is that only create a hard link to the file, cannot create points to the directory (also can actually, but more complex) and soft links can be, So soft links are more widely used.

Ln file1 file2 -> Create a hard link for file2Copy the code

If we use rm file1 to delete file1, there is no effect on file2. For hard links, deleting files on either side does not remove the contents of the files pointed to by both sides from the hard disk. Only after file1 and file2 are deleted at the same time, the contents of the files they point to disappear.

Soft links

Soft links are like shortcuts on Windows.

ln -s file1 file2
Copy the code

Run ls -l to view information about files in the current directory

total 0
-rw-r--r-- 1 root root 0 Jan 14 06:29 file1
lrwxrwxrwx 1 root root 5 Jan 14 06:42 file2 -> file1  # indicates that file2 points to file1
Copy the code

In fact, file2 is just a shortcut to file1. It points to file1, so it displays the contents of file1. If we delete file2, file1 will not be affected, but if we delete file1, file2 will become a dead link because the file is missing.

Users and Permissions

The user

Linux is a multi-user operating system. In Linux, in theory, we can create an infinite number of users, but these users are divided into different groups. One user, root, is a very special user who is the superuser and has the highest privileges.

Users created by ourselves are users with limited permissions, which greatly improves the security of the Linux system and effectively prevents misoperations or virus attacks. However, you can use the sudo command to execute some commands that require higher permissions.

sudo

Run the command as root

Sudo date --> Check the date without sudoCopy the code

useradd + passwd

  • useraddAdding a New User
  • passwdChanging a User password

These two commands require the root user permission

Useradd lion -> add a lion user, add /home path passwd lion -> change the lion user passwordCopy the code

userdel

To delete a user, you need the root user permission

Userdel lion -> deletes only the user name and does not delete the corresponding folder from /home userdel lion -> deletes the corresponding folder from /homeCopy the code

su

To switch to a user, you need the permission of the root user

Su -> switch to user root (exitTo switch to user root, run the following command: su lion -> Switch to user root su -> Switch to user rootCopy the code

Group Management

Every user in Linux belongs to a specific group. If you don’t set a group for the user, by default a group with the same user name will be created and the user will be assigned to that group.

groupadd

Create a group using the same method as userAdd.

groupadd friends
Copy the code

groupdel

Example Delete an existing group

Groupdel foo --> Delete group fooCopy the code

groups

View the user group

Groups lion --> View the groups that lion users belong toCopy the code

usermod

This command is used to modify a user account.

【 Common parameters 】

  • -lRename the user. One caveat/homeYou need to manually change the home directory name of the user in.
  • -gModify the group to which a user belongs, for exampleusermod -g friends lion Modify thelionThe user group isfriends 。
  • -GAllow users to add multiple groups at once, for exampleusermod -G friends,foo,bar lion
  • -a -GWill get you out of the group, and if you don’t want to do that, you’ll have to add it again-aParameter, meaningappendAdditional meaning.

chgrp

Group used to modify files.

CHGRP bar file. TXT --> file. TXT File group is changed to barCopy the code

chown

To change the owner of the file, you need root to run it.

Chown lion:bar file. TXT chown lion:bar file. TXT chown lion:barCopy the code

【 Common parameters 】

  • -RRecursively set subdirectories and subfiles,chown -R lion:lion /home/frankfrankFolder users and groups are changedlion 。

File Permission Management

chmod

Modify the access permission.

chmod 740 file.txt
Copy the code

【 Common parameters 】

  • -RYou can recursively modify file access permissions, for examplechmod -R 777 /home/lion

Modifying permissions is simple, but it is more important to understand their deeper meaning. Let’s learn the system Linux file permissions.

[root@lion ~]# ls -l
drwxr-xr-x 5 root root 4096 Apr 13  2020 climb
lrwxrwxrwx 1 root root    7 Jan 14 06:41 hello2.c -> hello.c
-rw-r--r-- 1 root root  149 Jan 13 06:14 hello.c
Copy the code

Drwxr-xr-x indicates the permission on a file or directory. Let’s read what it actually means.

  • d: indicates directory. That is, it is a directory-, the link isl
  • r : readIndicates that the file is readable.
  • w : writeIndicates that the file can be written. Generally, if the file has the write permission, the file can be deleted.
  • x : executeIndicates that the file is executable.
  • -: indicates no permission.

Permissions are divided by users as a whole, as shown in the figure below:

Drwxr-xr-x = drwxr-xr-x

  • It’s a folder;
  • Its owner has: read, write, execute permissions;
  • Its group users have the following permissions: read and execute, but no write permission.
  • Its other users have read and execute permissions, but not write permissions.

Now that we understand permissions, we use chmod to try to modify permissions. Chmod does not need to be root to run. As long as you are the owner of the file, you can use chmod to change the access to the file.

Digital assignment permission
permissions digital
r 4
w 2
x 1

So to change permissions, do some simple additions:

chmod 640 hello.c 

# analysis6 = 4 + 2 + 0 Indicates that the owner has the RW permission. 4 = 4 + 0 + 0 Indicates that the group user has the R permission. 0 = 0 + 0 + 0 Indicates that other users do not have the r permissionCopy the code
Use letters to assign permissions
  • u : userShort for user, which means owner.
  • g : groupGroup is an abbreviation for group users.
  • o : otherOther means other users.
  • a : allThe abbreviation for all means all users.
  • +: the plus sign indicates that the permission is added.
  • -: The minus sign indicates that the permission is removed.
  • =: Equals the sign, which indicates that permission is assigned.
Chmod u+rx file --> Owner of file adds read and run permission chmod g+r file --> Group user of file adds read permission chmod o-r file --> Other user of file removes read permission chmod G +r o-r file --> group user of file Remove read permission for other users chmod go-r file --> Remove read permission for other users chmod +x file --> Add run permission for all users of file chmod u= RWX,g=r,o= -file --> File The owner of the file assigns read/write and execute permissions to other users in the group. Other users do not have any permissionsCopy the code

Find files

locate

Search for all files and directories that contain the keyword. Followed by the file name you want to look for, you can also use regular expressions.

Install the locate

Yum -y install mlocate --> install package updatedb --> Update databaseCopy the code
locate file.txt
locate fil*.txt
Copy the code

[Note] The locate command searches the file database, not the full disk search, so the newly created file is not updated to the database, so it cannot be found. Instead, run the updatedb command to update the database.

find

To find files, it’s going to go through your actual hard drive to find them, and it allows us to follow up on each file that we find, and it’s very powerful.

What do you find?Copy the code
  • Where: Specifies which directory to look up, and all subdirectories of this directory will also be looked up.
  • What: What to look for, either by the name of the file, by its size, or by its last access time.
  • What to do: After the file is found, you can do subsequent processing. If this parameter is not specified,findThe command displays only the files found.

Search by file name

find -name "file.txt"--> Search for the file find.name in the current directory and subdirectories by name"syslog"--> Find / -name in the current directory and subdirectories by name"syslog"--> Search for the entire hard disk syslog find /var/log -name "syslog"--> In the specified directory /var/logCheck the syslog file find /var/log -name "syslog*"Syslog1, syslog2... The wildcard character indicates all find /var/log -name "*syslog*"--> Find the files that contain syslogCopy the code

[Note] The find command will only look for files that exactly match the “what” string, whereas locate will look for all files that contain the keyword.

Search by file size

Find/var-size +10M -> Search for files whose size exceeds 10M in the /var directory find/var-size -50k -> Search for files whose size is smaller than 50K in the /var directory find/var-size +1G --> Search for files whose size is 1 GB find/var-size 1M --> Search for files whose size is 1 MBCopy the code

Search by the last time the file was accessed

find -name "*.txt"- atime-7 --> Files ending in. TXT that have been accessed in the last 7 daysCopy the code

Look only for directories or files

find . -name "file" -typeF --> Only search for the file find.name in the current directory"file" -typeD --> Only search the file directory in the current directoryCopy the code

Operation search results

find -name "*.txt" -printf "%p - %u\n"--> Find all files with the suffix TXT and print them in %p - %u\n format, where %p= filename, %u= file owner find-name"*.jpg"-delete --> Delete all files in the current directory and subdirectories with the suffix. JPG. Therefore, use find-name with caution"*.c" -execchmod 600 {} \; --> Do - for every.c ending fileexecThe operation specified by the {} argument is replaced by the found file, \; Is the required find-name"*.c"-ok chmod 600 {} \; --> and the above function, will be an additional confirmation promptCopy the code

repositories

In Linux, software exists in the form of a package. A software package is actually a compressed package of all the files of the software. It is in binary form and contains all the instructions for installing the software. Red Hat software packages are named after.rpm. Debian software packages are named after.deb.

Linux packages have a repository called the Software Repository, which can be used to manage packages using yum, the default package management tool in CentOS. Yum is available for Red Hat families. This can be thought of as node.js NPM.

Yum Common Commands

  • yum update | yum upgradeUpdating software Packages
  • yum search xxxSearch for the appropriate package
  • yum install xxxInstalling Software Packages
  • yum remove xxxDeleting a Software Package

Example Switch the CentOS software source

Sometimes CentOS default yum source is not necessarily a domestic image, resulting in the yum online installation and update speed is not very good. You need to set the yum source as a domestic mirror site. The major open source mirror sites in China are netease and Aliyun.

1. Backup the system’s yum source configuration file mv /etc/yum-repos. d/ centos-base. repo /etc/yum-repos. d/ centos-base. repo

/etc/yum. Repos. D /CentOS7

wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
Copy the code

3. Generate the cache

yum makecache
Copy the code

Read the manual

Linux commands are so complex that we can’t remember them all by memory, so it’s important to learn how to use the manual.

man

Install update man

Sudo yum install -y man-pages --> install sudo mandb --> updateCopy the code

Man Manual Types

  1. Executable program orShellCommand;
  2. System call (LinuxKernel provided functions);
  3. Library calls (functions in a library);
  4. Files (e.g./etc/passwd);
  5. Special files (usually in/devBelow);
  6. The game;
  7. Miscellaneous (man(7) ,groff(7));
  8. System administration commands (usually can only be used byrootUser use);
  9. Internal nuclear program.

Man + number + command

Enter man + number + command/function to query related commands and functions. If no number is added, man searches for related commands and functions from manuals with smaller numbers by default

Man 3 RAND --> find the RAND function man ls --> find the LS usage manualCopy the code

Man manual core area parsing :(take man PWD as an example)

NAME # Command name and brief description
     pwd -- return working directory name

SYNOPSIS # Use all methods of this command
     pwd [-L | -P]

DESCRIPTION # includes all parameters and usage
     The pwd utility writes the absolute pathname of the current working directory to the standard output.

     Some shells may provide a builtin pwd command which is similar or identical to this utility.  Consult the builtin(1) manual page.

     The options are as follows:

     -L      Display the logical current working directory.

     -P      Display the physical current working directory (all symbolic links resolved).

     If no options are specified, the -L option is assumed.

SEE ALSO Extension read related commands
     builtin(1), cd(1), csh(1), sh(1), getcwd(3)
Copy the code

help

The man command can query the detailed information of the command or function like xinhua Dictionary, but in fact, we have a faster way to query, command –help or command -h, it is not as detailed as the man command, but it is easier to read.

Linux advanced

Text manipulation

grep

Search a regular expression globally and print it to the screen. In simple terms, look for a keyword in the file and display the line where the keyword is located.

Basic grammar

grep text file # text indicates the text to be searched, and file indicates the file to be searched

Example #
[root@lion ~]# grep path /etc/profile
pathmunge () {
    pathmunge /usr/sbin
    pathmunge /usr/local/sbin
    pathmunge /usr/local/sbin after
    pathmunge /usr/sbin after
unset -f pathmunge
Copy the code

Commonly used parameters

  • -iIgnore case,grep -i path /etc/profile 
  • -nShow the line number,grep -n path /etc/profile
  • -vDisplays only those lines where the search text is not present,grep -v path /etc/profile
  • -rRecursive search,grep -r hello /etc, Linux also has an rgrep command, which is equivalent togrep -r 

Advanced usage

Grep can be used with regular expressions.

Grep -e ^path /etc/profile --> Matching path grep -e ^path /etc/profile --> Matching the character string beginning with path grep -e [Pp]ath /etc/profile --> Matches path or PATHCopy the code

sort

Sort the lines of the file.

Basic grammar

sort name.txt # sort the name.txt file
Copy the code

Examples of usage

For the sake of illustration, let’s first create a file named. TXT and put the following contents in it:

Christopher
Shawn
Ted
Rock
Noah
Zachary
Bella
Copy the code

The sort name.txt command sorts the text contents.

Commonly used parameters

  • -oWrite the sorted file to a new file,sort -o name_sorted.txt name.txt ;
  • -rIn reverse order,sort -r name.txt ;
  • -RRandom sorting,sort -R name.txt ;
  • -nSorting numbers, by default, recognizes numbers as strings, so 138 will rank before 25 if added-nIn numerical order, 25 would come before 138.

wc

Abbreviation for word count, used for counting files. It can count the number of words, lines, characters, bytes, and so on.

Basic grammar

wc name.txt # statistical name. TXT
Copy the code

Examples of usage

[root@lion ~]# wc name.txt 
13 13 91 name.txt
Copy the code
  • The first 13 is the number of rows;
  • The second 13, the number of words;
  • The third, 91, represents the number of bytes.

Commonly used parameters

  • -lJust count the number of rows,wc -l name.txt ;
  • -wJust count the words,wc -w name.txt ;
  • -cOnly bytes are counted,wc -c name.txt ;
  • -mOnly count the number of characters,wc -m name.txt 。

uniq

Delete duplicate files.

Basic grammar

uniq name.txt # Remove duplicate lines from name.txt and print to screen
uniq name.txt uniq_name.txt # Save the deduplicated file as uniq_name. TXT
Copy the code

[Note] It can only remove the number of consecutive repeated lines.

Commonly used parameters

  • -cCount the number of repeated rows,uniq -c name.txt ;
  • -dDisplays only the number of duplicate lines,uniq -d name.txt 。

cut

Cut a section of a file.

Basic grammar

cut -c 2-4 name.txt # Cut the second to fourth characters of each line
Copy the code

Commonly used parameters

  • -dUsed to specify what delimiter to use (such as comma, semicolon, double quotation marks, and so on)cut -d , name.txt ;
  • -fWhich area or areas to cut off with a delimiter,cut -d , -f 1 name.txt 。

Redirect the pipeline flow

inLinuxThere are three places where a command can go: a terminal, a file, or as an input to another command.



A command is usually typed on a keyboard and then output to a terminal, file, etcstdin 、 stdoutAs well asstderr 。

  • The standard inputstdin, the terminal receives the keyboard input command, will produce two kinds of output;
  • The standard outputstdout, the terminal output information (excluding error information);
  • Standard error outputstderr, the terminal output error information.




redirect

Send the result of a command that is intended to be displayed on the terminal somewhere else (to a file or as input to another command).

Output redirection> 

Cut -d, -f 1 notes.csv > name.csv, which means to cut the notes.csv file (which has three parts) with a comma to get the first part and redirect it to the name.csv file. Let’s take a look at a concrete example to learn how to use it. Suppose we have a file called notes.csv that reads like this:

Mark1,951/100, it is very nice1
Mark2,952/100, it is very nice2
Mark3,953/100, it is very nice3
Mark4,954/100, it is very nice4
Mark5,955/100, it is very nice5
Mark6,956/100, it is very nice6
Copy the code

Run the following command: cut -d, -f 1 notes.csv > name. CSV The following information is displayed:

Mark1
Mark2
Mark3
Mark4
Mark5
Mark6
Copy the code

Note that if the output file does not exist, it will create a new one. If the output file already exists, it will be overwritten. So do this with great care to avoid overwriting other important files.

Output redirection>> 

Indicates redirection to the end of the file, so it is not as dangerous as the > command, which is appended to the end of the file (of course, if the file does not exist, it will also be created). Run cut -d, -f 1 notes.csv >> name.csv again to append the name to name.csv.

Mark1
Mark2
Mark3
Mark4
Mark5
Mark6
Mark1
Mark2
Mark3
Mark4
Mark5
Mark6
Copy the code

We usually read the log file is actually using this command output.

Output redirection2 > 

Standard error output

cat not_exist_file.csv > res.txt 2> errors.log
Copy the code
  • When wecatWhen you have a file, you print the contents of that file to the screen, so this is standard output;
  • When using the> res.txtInstead of printing to the screen, the standard output is written to a fileres.txtFile;
  • 2> errors.logWrites when an error occurserrors.logFile.

Output redirection2 > > 

The standard error output (appended to the end of the file) is similar to >>.

Output redirection2 > &1 

Both standard output and standard error output redirect to the same place

cat not_exist_file.csv > res.txt 2> &1# Overwrite the output cat not_exist_file. CSV >> res.txt2> &1# Append outputCopy the code


So far, all the commands we’ve been dealing with have input from the command’s arguments, but the input can also come from a file or from the keyboard.





Input redirection< 

The < symbol is used to specify the input of the command.

Cat < name.csv # specifies the command input as name.csvCopy the code

It works the same as cat name.csv, but the principle is completely different.

  • cat name.csvsaidcatCommand receives the following inputnotes.csvFile name, then open the file and print out the contents.
  • cat < name.csvsaidcatThe input received by the command isnotes.csvThe contents of this file,catThe command simply prints its contents, opens the file, and passes the file contents tocatThe command is left to the terminal.

Input redirection<< 

Redirects keyboard input to a command input.

Sort -n << END # after entering this command, press Enter, and the terminal enters the keyboard mode, where END is the command (this can be customized) wc -m << END # counts the words enteredCopy the code

The pipe| 

To use two commands in conjunction, with the output of one as the input of the otherpipelineYou can imagine that pipes are connected. Pipes are a kind of redirected flow.







A few practical usage examples:

cut -d , -f 1Name. The CSV | sort > sorted_name. TXT #, the first step to get to the name list by pipeline operators to sort, The final output to sorted_name. TXT du | sort - nr | head # # du said list directory size information sort sorting, -n said press numeric sorting, -r said # before head in reverse chronological order10Grep log -ir /var/log | cut -d : -f 1 | sort | uniq
# grep log -Ir /var/log means to search for/in the log foldervar/log text, -r for recursion, and -i for excluding binaries # cut -d: -f1# uniq # uniq # uniq # uniq # uniq # uniqCopy the code

flow

A stream is not a command. In computer science, the meaning of a stream is difficult to understand. Just remember that a stream is reading a little bit of data and processing a little bit of data. The data is usually in binary format. The redirection, or pipeline, mentioned above, operates data as a stream. This brings us to the advanced Linux concepts and directives of streams, redirects, pipes, and so on. In fact, you’ll find a wide range of applications for streams and pipes in other languages. Pipes can be used in Angular template syntax. Node.js also has the concept of a stream.

Check the process

On Windows, run the Ctrl + Alt + Delete shortcut keys to view software processes.

w

Helps us quickly understand which users are currently logged in to the system and what they are doing.

[root@lion ~]# w
 06:31:53 up 25 days,  9:53.1 user,  load average: 0.00.0.01.0.05
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
root     pts/0    118.31243.53.    05:56    1.00s  0.02s  0.00s w
 
06:31:53: indicates the current time up25 days, 9:53: indicates that the system is running properly.25day9hours53Minutes."1User: indicates a user load average:0.00.0.01.0.05: indicates the load of the system.3Each value represents"1Average load per minute ","5Average load per minute ","15Load average per minute "USER: indicates the login used for TTY: The login terminal is named PTS /0FROM: IP address used to connect to the server login@ : LOGIN time IDLE: How long has the user been inactive JCPU: CPU time used by all processes associated with the terminal. The time is stopped when a process ends and restarted when a new process starts. PCPU: WHAT: WHAT is the program that the user is running at the moment. In this case, I'm running wCopy the code

ps

The list of processes displayed by the ps command does not change over time. It is a static list of processes, or a snapshot of the processes at the time the ps command is run.

Basic grammar

[root@lion ~]# ps
  PID TTY          TIME CMD
 1793 pts/0    00:00:00 bash
 4756 pts/0    00:00:00Ps PID: indicates the process ID. Each process has a unique process ID. TTY: indicates the terminal where the process is running. TIME: indicates the TIME when the process is runningCopy the code

Commonly used parameters

  • -efList all processes;
  • -efHList all processes as trees;
  • -uLists the processes that this user is running;
  • -auxthroughCPUAnd memory usage to filter processesps -aux | less ;
  • -aux --sort -pcpu 按 CPUUsing descending order,-aux --sort -pmemIndicates the descending order of memory usage.
  • -axjfDisplays processes in a tree structure,ps -axjfIt andpstreeThe effect is similar.

top

Gets a dynamic list of processes.

top - 07:20:07 up 25 days, 10:41.1 user,  load average: 0.30.0.10.0.07
Tasks:  67 total,   1 running,  66 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.7 us,  0.3 sy,  0.0 ni, 99.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
KiB Mem :  1882072 total,   552148 free,   101048 used,  1228876 buff/cache
KiB Swap:        0 total,        0 free,        0 used.  1594080 avail Mem 

  PID USER      PR  NI    VIRT    RES    SHR S %CPU %MEM     TIME+ COMMAND                                                                                                       
  956 root      10 -10  133964  15848  10240 S  0.7  0.8 263:13.01 AliYunDun                                                                                                     
    1 root      20   0   51644   3664   2400 S  0.0  0.2   3:23.63 systemd                                                                                                       
    2 root      20   0       0      0      0 S  0.0  0.0   0:00.05 kthreadd                                                                                                      
    4 root       0 -20       0      0      0 S  0.0  0.0   0:0000. kworker/0:0H    
Copy the code
  • Top-07:20:07 up 25 days, 10:41, 1 user, load average: 0.30, 0.10, 0.07Quite awThe first line of the command.
  • These processes are shown in terms of using the processor%CPUTo sort by usage.

kill

To kill a process, kill + PID.

kill 956# End process id is956The process of the kill956 957# Kill multiple processes kill -9 7291# Forcibly end the processCopy the code

Management process

Process status

The process status is changed. Let’s take a look at the five states of processes in Linux:

  1. Status codeR: indicates the running status.
  2. Status codeS: indicates interruption (in hibernation, blocked, when a condition is formed or when a signal is received, to leave the state);
  3. Status codeD: indicates that the process cannot be interrupted. The process does not respond to asynchronous signals. The process cannot be interrupted even by running the kill command.
  4. Status codeZ: indicates rigidly dead (the process has been terminated, but the process descriptor persists until called by the parent processwait4()Release process after system function);
  5. Status codeT: indicates stop (process receivedSIGSTOP 、 SIGSTP 、 SIGTIN 、 SIGTOUWait for the stop signal to stop operation).

Foreground process & Background process

By default, user-created processes are foreground processes, which read data from the keyboard and output the results to the display. For example, by running the top command, this is a foreground process that is always running.

The advantage of background processes is that you don’t have to wait for the program to finish, so you can type other commands. To start a background process, add the ampersand after the command that needs to be executed.

&

The disadvantage of starting the background process is that the background process is associated with the terminal, and once the terminal is closed, the process automatically ends.

cp name.csv name-copy.csv &
Copy the code

nohup

Make the process immune to hang up (closing a terminal, etc.).

nohup cp name.csv name-copy.csv
Copy the code

The nohup command can also be used in combination with &.

nohup cp name.csv name-copy.csv &
Copy the code

bg

Change the status of a paused background process to Background Running.

bg %1# If you don't take any arguments, the bg command defaults to the nearest background process. If you take any arguments, the bg command defaults to the specified processCopy the code

Actual Case 1:

1.Perform the grep -r"log" / > grep_log 2> &1Command to start a foreground process and forgot to add the & symbol2.CTRL + Z changes the process state to background pause3.Run bg to convert the command to run in the backgroundCopy the code

Actual Case 2:

In front end development, we often do yarn start to start the project and then we hit CTRL + Z to pause it and then we run bg to make it run in the background so that the current terminal is free to do other things, if you want to wake it up you just use fg (more on that later)Copy the code

jobs

Display the background process status of the current terminal.

[root@lion ~]# jobs
[1]+  Stopped                 top
[2]-  Running                 grep --color=auto -r "log" / > grep_log 2> &1 &
Copy the code

fg

fgConvert the process to foreground running, usage andbgCommands are similar.



Let’s use a graph to show the foreground and background process switch:







We can make the program run in the background, as a background process, so that we can do other things in the current terminal instead of waiting for the process to finish.

daemon

A running program is called a process. Some processes in Linux are special in that they are not associated with any process, they run in the background regardless of the user’s identity, and their parent process is a process with PID 1, which is destroyed only when the system is shut down. They just keep running in the background waiting for work to be assigned. We call these processes daemons.

Daemons usually have a d at the end, meaning daemon, such as systemd or HTTPD.

systemd

Systemd is a collection of basic Linux system components that provide a system and service manager that runs as PID 1 and is responsible for starting other programs.

[root@lion ~]# ps -aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.2  51648  3852 ?        Ss   Feb01   1:50 /usr/lib/systemd/systemd --switched-root --system --deserialize 22
Copy the code

You can also see that a process with PID 1 is a system process. Systemd common commands (which are a collection of commands) :

Systemctl restart nginx # Restart the service systemctl status nginx # Check the service status Systemctl disable nginx # Reload nginx # reload nginx # Systemctl is-enabled nginx # Check whether services are automatically started upon startup. Systemctl list-unit-files --type=service # Check whether services are started and disabled at different levelsCopy the code

File decompression

  • Packaging: multiple files into a total file, its scientific name is archive, archive.
  • Compression: The compression of a large file (usually an archive) into a smaller file.


We often usetarTo archive multiple files into a single total file, calledarchive. And then usegzip 或 bzip2Command willarchiveCompress to smaller files.



tar

Create a tar archive.

Basic usage

Tar tar -cvf sort.tar sort/ # Archive the sort folder as sort.tar tar -cvf archive.tar file1 file2 file3 # File file1 file2 file3 Archive for the archive. The tarCopy the code

Commonly used parameters

  • -cvfsaidcreate(Create) +verbose(details) +file(file), creating an archive file and displaying operational details;
  • -tfDisplays the contents of the archive without unlocking the archive;
  • -rvfAppend files to the archive,tar -rvf archive.tar file.txt ;
  • -xvfUnlock the archive,tar -xvf archive.tar 。

gzip / gunzip

By default, the gzip command is used to archive the compressed file. The file name extension is.tar.gz.

Gzip archive.tar # zip gunzip archive.tar.gz # zip gunzip archiveCopy the code

Tar archive + compression

You can use tar to archive and compress at the same time by adding an option to tar so that after the archiving is complete, you can still use gzip or bzip2 to compress.

Gz archive/ # Archive the archive folder and compress it. Tar -zxvf archive.tar.gz # Decompress the archive archiveCopy the code

Zcat, Zless and Zmore

You can view the contents of a file using cat less more, but you can’t view the contents of a compressed file using these commands. Instead, you can view the contents of a compressed file using zcat, zless, and zmore.

zcat archive.tar.gz
Copy the code

zip/unzip

Zip/Decompress. Zip files are usually from Windows operating systems.

Command to install

# yum install zip yum install unzipCopy the code

Basic usage

Zip -r sort.zip sort/ # unzip the sort.zip folder to sort.zip, -r indicates recursionCopy the code

Compiling the installation Software

We learned how to install software using the YUM command, and if we encounter software that is not in the YUM repository, we need to use the more advanced “source compile install” software installation.

Compile the installation

Simply put, compilation is the process of converting a program’s source code into an executable file. Most Linux programs are open source and can be compiled into executable files that fit our computer and manipulate system properties. The basic steps are as follows:

  1. Download the source code
  2. Decompressing a Compressed Package
  3. configuration
  4. compile
  5. The installation

The actual case

1, download

Let’s compile and install htop software, first download the source code in its official website: bintray.com/htop/source… The downloaded source code is synchronized to the server using the following command on the local computer:

SCP file name Username @Server IP address: destination path SCP ~/Desktop/htop-3.0. 0.tar.gz root@121.4211.34.:.
Copy the code

You can also download it using Wegt:

Wegt + download from wegt HTTPS:/ / bintray.com/htop/source/download_file?file_path=htop-3.0.0.tar.gz
Copy the code
2. Decompress the file
tar -zxvf htop-3.0. 0Gz # Decompress CD htop-3.0. 0# enter directoryCopy the code
3, configuration,

Run./configure, which analyzes your computer to make sure all the tools needed for the compilation are installed.

4, compile,

Run the make command

5, installation,

Run the make install command. After the installation is complete, run ls /usr/local/bin/to check whether the htop command exists. If yes, run the htop command to view the system process.

network

ifconfig

Check the IP network information. If the command does not exist, run the yum install net-tools command to install it.

[root@lion ~]# ifconfig

eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 172.3124.78.  netmask 255.255240.. 0  broadcast 172.3131.255.
        ether 00:16:3e:04:9c:cd  txqueuelen 1000  (Ethernet)
        RX packets 1592318  bytes 183722250 (175.2 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 1539361  bytes 154044090 (146.9 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0. 01.  netmask 255.0. 0. 0
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
Copy the code

Parameter analysis:

  • eth0A wired connection (your wired network card) is a network cable connected to the Internet.eth 是 EthernetAbbreviation for Ethernet, which stands for Ethernet. Some computers may have more than one network cable at a time, such as a servereht0You’ll also seeeth1 、 eth2And so on.
  • loRepresents a local loop (Local LoopbackThe abbreviation for a virtual network adapter) can see itipThe address is127.0.0.1. Every computer should have this interface because it corresponds to a “link to itself.” That’s why it’s called a “local loop.” Everything sent through this interface goes back to your own computer. It doesn’t seem to work, but sometimes we need to connect ourselves for some reason. For example, to test a network program, but do not want to let LAN or external users to view, can only run on this host and view all network interfaces. For example, when we start a front-end project, we type in the browser127.0.0.1:3000Start the project and see your ownwebWebsite, and only you can see it.
  • wlan0Represents wireless LAN (not shown in the example above).

host

The IP address is translated into the host name.

Software installation

yum install bind-utils
Copy the code

Basic usage

[root@lion ~]# host github.com
baidu.com has address 13.229188.59.
 
[root@lion ~]# host 13.229188.59.
59.188229.13..in-addr.arpa domain name pointer ec2-13-229-188-59.ap-southeast-1.compute.amazonaws.com.
Copy the code

SSH Connection to the remote server

Asymmetric encryption and symmetric encryption (similar to HTTPS) are used to connect to the remote server.

SSH user @ IP: port1, SSH root @172.2010.1.:22# Port number can be omitted, default is22port2, enter the connection password to operate the remote serverCopy the code

Configure SSH

You can configure SSH in the config file, which facilitates batch management of multiple SSH connections. Configuration files are classified into the following types:

  • globalsshServer configuration:/etc/ssh/sshd_config ;
  • globalsshClient configuration:/etc/ssh/ssh_config(rarely modified);
  • The current usersshClient configuration:~/.ssh/config 。

[Common configuration parameters of the server Config file]

Config parameters on the server role
Port SSHD Service port number (default: 22)
PermitRootLogin Whether to allow login as the root user (yes by default)
PasswordAuthentication Whether to allow password authentication for login (yes by default)
PubkeyAuthentication Whether to allow public key authentication for login (yes by default)
PermitEmptyPasswords Whether to allow login with an empty password (insecure, default not allowed)

[Caution] After modifying the configuration file on the server, restart the service. Systemctl restart SSHD

The client config parameter role
Host The alias
HostName Remote host name (or IP address)
Port The port connected to the remote host
User The user name

Config for the current user:

Create config vim ~/.ssh/Config # Host lion # alias HostName172.X.X.X # IP address Port22User root UserCopy the code

After the configuration is complete, the next time you log in to SSH Lion, you can automatically identify the root user. [Note] This configuration is not on the server, but on your own machine. It just sets an alias.

Avoid close login

There are two types of SSH login: password-based (account password) and key-based. Based on the password, is each login to enter the account and password, obviously this is more troublesome, today mainly learn how to achieve the secret based on the key login.

Based on the principle of key authentication

The client generates a key pair (public key and private key) and uploaks the public key to the server. Each login is compared with the public key of the server. This method of authenticating login is more secure and is also called “public key authenticated login”.

Specific implementation Steps

Ssh-keygen generates two files in the ~/. SSH/directory:

  • id_rsa.pub: the public key
  • id_rsaThe private key:

2. To pass the client’s public key to the service, run the ssh-copy-id [email protected] (ssh-copy-id appends the client’s public key to the server ~/.ssh/authorized_keys file). Run SSH [email protected] to log in to the server without password.

With the above set alias, directly execute SSH Lion can log in, is not very convenient.

wget

Allows us to download files directly from the terminal console, simply by giving the HTTP or FTP address of the file.

Wget [parameter][URL address] wget HTTP:/ / www.minjieren.com/wordpress-3.1-zh_CN.zip
Copy the code

Wget is very stable. If the download fails due to network reasons, Wget will try again and again until the entire file has been downloaded.

Commonly used parameters

  • -cContinued interrupted download.

The backup

scp

It is short for Secure Copy, which stands for Secure Copy. SCP enables us to copy files from one computer to another over the Internet. SCP operates on the basis of SSH, which creates a secure communication pipeline between two computers connected over a network. SCP uses this pipeline to securely copy files.

SCP source_file destination_file # source_file indicates the source file, destination_file indicates the destination fileCopy the code

Both source_file and destination_file can be represented as: user@ip:file_name, user is the login name, and IP is the domain name or IP address. File_name is the file path.

scp file.txt root@192.1681.. 5:/root # : copy file. TXT from the current folder on my computer to the remote computer SCP root@192.1681.. 5:/root/File.txt file.txt # copies file.txt files from the remote computer to the local computerCopy the code

rsync

The rsync command is used to remotely synchronize files. It synchronizes two directories, whether they are on the same computer or not. This is probably the most common “incremental backup” command. It is the intelligent version of the SCP command.

Software installation

yum install rsync
Copy the code

Basic usage

Rsync-arv Images/ backups/ # Backups of all files in the Images directory to rsync-arv Images/ root@192.X.X.X :backups/ # Syncing to the backups of the serverCopy the code

Commonly used parameters

  • -aRetain all information about the file, including permissions, modification date, etc.
  • -rRecursive call to indicate that all files in the subdirectory are also included;
  • -vIn redundancy mode, detailed operation information is displayed.

By default, rsync does not delete files in the target directory when synchronizing. For example, if you delete a file in the source directory, it does not delete the same file in the synchronized directory. You can do the same for delete: rsync-arv –delete Images/ backups/.

system

halt

To shut down the system, you need to be root.

halt
Copy the code

reboot

To restart the system, you need to be the root user.

reboot
Copy the code

poweroff

Run directly to shut down, no root identity is required.

Vim editor

What is Vim?

Vim is a text editor developed from VI. Its code completion, compilation and error jump and other convenient programming functions are particularly rich, is widely used in programmers. Tied with Emacs as the favorite editor for users of UniX-like systems.

Vim common mode

  • Interactive mode
  • Insert mode
  • Command mode
  • Visual model

Interactive mode

This is Vim’s default mode, and every time you run a Vim program, you go into this mode. For example, executing vim name.txt will enter interactive mode. Characteristics of interaction mode:

  • In this mode, you cannot enter text;
  • It allows us to move between text, delete a line of text, copy and paste text, jump to specified lines, undo operations, and so on.

Insert mode

This mode is a familiar text editor mode, where you can type anything you want. There are several ways to enter this mode, the most common is to press the letter key I (I, I, a, A, O, o can all go into insert mode, but in different positions), and to exit this mode, just press the Esc key.

  • i, IEnter input modeInsert mode : iIs “Enter from the current cursor position”,I“Start typing at the first non-space character on the current line”;
  • a, AEnter input modeInsert mode : aIs “Start at the next character where the cursor is currently located”,AIs “Start at the last character of the line where the cursor is located”;
  • o, OEnter input modeInsert mode : oEnter a new line next to the current line where the cursor is located.OEnter a new line above the current line with the cursor.

Command mode

The command mode is also called the bottom-line command mode. In this mode, you can run commands such as “exit” and “Save”.



You can also use this mode to activate someVimConfiguration, such as syntax highlighting, displaying line numbers, etc. You can even send some commands to the terminal command line, for exampleLs, cp, 。



To enter command mode, first enter interactive mode and then press the colon key.



A graph shows how the three modes are toggled:



Basic operation

Open the Vim

Enter vim on the terminal command line and press Enter to run vim. You can also use vim to open a file by adding the name of the file after vim. For example, vim file.name, if the file does not exist, it will be created.

insert

After entering the file, you are in interactive mode and can enter insert mode by typing I.

mobile

In Vim’s interactive mode, we can move the cursor through the text.

  • hMove one character to the left
  • jMove down one character
  • kMove up one character
  • iMoves one character to the right

Of course, you can also use the four arrow keys to move, the effect is the same.

Skip to the beginning and end of a row

  • Start of line: In interactive mode, to move the cursor to the start of a line, simply press a number key0Yes, it’s on the keyboardHomeA key has the same effect.
  • End of line: In interactive mode, to move the cursor to the end of a line, simply press the dollar sign key$Yes, it’s on the keyboardEndA key has the same effect.

Move by word

In interactive mode, press the letter key W to move word by word.

Exit the file

In interactive mode, press the colon key to enter command mode, and then press the Q key to exit. If you want to exit Vim with :q after modifying the file before exiting, Vim will display a red letter error message. At this point we have two choices:

  1. Save and Exit:wq  或 :x
  2. Exit without saving:q!

Standard operating

Delete the character

In interactive mode, place the cursor over a character you want to delete, press the letter key x and you will see that the character is deleted. You can also delete more than one character at a time by entering the number before pressing the X key.

Delete (cut) words, lines

  • To delete a line, press twicedTo delete the line where the cursor is.
  • Delete multiple lines: For example, enter a number first2, and then pressdd, the two lines starting with the cursor line are deleted.
  • To delete a word: Place the cursor at the first letter of a word and pressdw 。
  • Delete multiple words: for example, press a number key first2thendwYou can delete two words.
  • Delete from cursor position to the beginning of line:d0 。
  • Delete from cursor position to end of line:d$ 。

Copy the words, the lines

  • Copy line: Press twiceyWill copy the cursor line into memory, andddA similar,ddUsed to cut the line where the cursor is located.
  • Copy the words:ywWill copy a word.
  • Copy to the end of the line:y$Is to copy all characters from where the cursor is to the end of the line.
  • Copy to the beginning of the line:y0Is to copy all characters from the cursor to the beginning of the line.

paste

If you cut and copy it with DD or YY, you can paste it with P. You can also use the number +p for multiple copies.

Replace a character

In interactive mode, place the cursor over the character you want to replace. Press r and enter the character you want to replace.

Cancel the operation

To undo the most recent changes, just press the U key. To undo the last four changes, press 4 and then press U.

redo

Cancel undo, that is, redo previous changes using CTRL + R.

Jumps to the specified line

In Vim’s edited files, each line has a line number that starts at 1 and increases increments. Line numbers are not displayed by default. If you want them to be displayed, go to command mode and type set nu. If you want them to be hidden, use set nonu.

  • Jump to the specified line:Digital + gg, e.g.7ggTo jump to line 7.
  • To jump to the last line, pressG 。
  • To jump to the first line, pressgg 。

Advanced operation

To find the

In interactive mode, press the/key, then enter search mode, enter the string you are looking for, and press Enter. The cursor will jump to the next match found in the file. If the string does not exist, “Pattern not found” is displayed.

  • nJump to the next match;
  • NJumps to the previous match.

[Note] A search with a slash starts at the current cursor and searches toward the end of the file. If you want to start at the current cursor and search toward the header, use? Of course, you can also press gg to jump to the first line in the full text search.

Find and replace

Replace the first matching string in the cursor line:

Example :s/one/twoCopy the code

Replace all old strings in the cursor line with the new string:

Syntax :s/ old string/new string /gCopy the code

Replace all strings from line to line:

N,m s/ old string/new string /g2.4 s/one/two/g
Copy the code

The most common is to replace the full text:

# Syntax :%s/ old string/new string /gCopy the code

Merge files

The colon +r (:r) is used to insert the contents of a file at the cursor.

:r filename # Can automatically complete the path of another file with the Tab keyCopy the code

Split screen

One particularly handy feature of Vim is a split screen, which allows you to have several files open at the same time. After the split screen, each piece of the screen is called a Viewport, meaning “viewport.”

  • The horizontal split screen: sp filename
  • Vertical split screen: VSP filename

Shortcut keys in split screen mode

  • Ctrl + waddCtrl + wWhich means from aviewportMove the cursor to anotherviewport ;
  • Ctrl + wAdd “arrow keys”, you can move to the direction of the next viewport;
  • Ctrl + wadd+, which means to expand the current viewport;
  • Ctrl + wadd-, which means to narrow the current viewport;
  • Ctrl + wadd=Is the average current viewport;
  • Ctrl + waddrKey, will reverse the position of the port;
  • Ctrl + waddqKey, will close the current viewport;
  • Ctrl + waddoKey, will close all viewports except the current viewport;

Running external commands:!

You can run some terminal commands in Vim by first typing :! , and then take the command name. Such as:

:! Ls # Run the ls command in the directory where the files opened in Vim are locatedCopy the code

Visual model

There are only three modes of Vim, but there is also a mode called visual mode. There are three ways to enter it (all from interactive mode) :

  • vCharacter visual mode, enter with arrow keys to select the character, and then pressdKey to delete the selected.
  • VRow visible mode, enter the cursor line is selected by default, and then pressdKey can delete the row.
  • Ctrl + vBlock visual mode, it is the most useful feature of visual mode, withd  和 IKey to delete selected content and insert content.

To select multiple rows at the same time and insert the content in the head of the selected row:

1.CTRL + V to enter block view mode2.Select using arrow keys (up, down, left, right) Assume selected5line3.Enter I to insert multiple lines at the same time4.After the insert is complete, press the ESC key twice to insert the same character in multiple lines at the same timeCopy the code

Operation keys after entering visual mode:

  • dKey: deletes selected;
  • IKey to insert before selected;
  • uKey, it is selected to lowercase.
  • UKey: indicates that the value is selected to uppercase.

Vim configuration

Option parameters

After Vim is started, you can run instructions to activate some option parameters, but the configuration of these option parameters, such as the activation line number described earlier, will be forgotten when you exit Vim. If you want the configuration to be permanent, you need to create a Vim configuration file.vimrc in your home directory (CD ~).

.vimrc

set number "Display line number syntax on"Activate syntax highlight set showcmd"See the command set ignorecase in real time"Search with case-insensitive set mouse=a"Activate the mouse. When selected with the mouse, it is equivalent to entering visual modeCopy the code

The Vim configuration is so rich that we can personalize Vim to make it our own IDE and so on. Some powerful Vim profiles are also available on Github.

conclusion

I believe that after learning this article, you should have a more comprehensive understanding of Linux.

If you see here, just go to 👍 👍 👍.