Portal:By the end of this article, you’ll have the basics of Python

The Linux foundation

This article is based on the 2016 Gitbook and video materials of The Transwise Podcast, and also incorporates some content of the 2018 video and courseware materials, which is based on the data of 2016 and assisted by the data of 2018.

I. Introduction to Linux

1. Development of operating system

2. Different versions of Linux

<1> Version of the Linux kernel: The kernel is the heart of the system. It is the core program that runs programs and manages hardware devices like disks and printers. It provides an abstraction layer between bare devices and applications. <2>Linux distribution: also known as GNU, usually contains applications including desktop environments, office suites, media players, databases, etc.

2. Files and directories

1. Differences between Windows and Linux file systems

In Windows, open “computer”, we see a drive letter:

/ : Root directory. Generally, only directories are stored under the root directory. In Linux, there is only one root directory. Everything starts here. When you type “/home” in a terminal, you’re telling the computer to start at/and then go to the home directory. /bin: /usr/bin: directory for executing binary files, such as ls, tar, mv, and cat commands. /boot: Stores files used during the startup of the Linux system, such as the Linux kernel file /boot/vmlinuz, and the system boot manager file /boot/grub. To access a file in this directory is equivalent to accessing a device. The common method of mounting a CD/DVD-ROM drive is mount /dev/cdrom/MNT. You are not advised to store executable files in this directory. Important configuration files include /etc/inittab, /etc/fstab, /etc/init.d, /etc/x11, /etc/sysconfig, and /etc/xinetd.d. /home: the default user home directory. When a user account is added, the user’s home directory is stored in this directory. ~ indicates the home directory of the current user, and ~edu indicates the home directory of the user. /lib: /usr/lib: /usr/local/lib: directory of the function library used by the system. The function library is required to call additional parameters during program execution. /lost+fount: This is where some missing fragments will be placed when system exceptions produce errors. / MNT: /media: indicates the default mount point of the CD. Usually, the CD is mounted under/MNT /cdrom, but it is not necessary. You can mount the CD anywhere. /opt: specifies the directory for storing additional installation software on the host. The/proc: The data in this directory is stored in memory, such as system core, external devices, and network status. Since the data is stored in memory, it does not occupy disk space. Important directories include /proc/cpuinfo, /proc/interrupts, /proc/dma, /proc/ioports, and /proc/net/*. /root: home directory of the system administrator root. /sbin: /usr/sbin: /usr/local/sbin: stores the executable commands used by the system administrator, such as fdisk, shutdown, and mount. Different from /bin, these directories are commands used by the system administrator root. Common users can only “view” these commands, but cannot set or use them. / TMP: directory where files are temporarily stored by common users or running programs. Anyone can access this directory. Important data cannot be stored in this directory. / SRV: indicates the directory of data to be accessed after the service is started. For example, the web page data to be accessed by the WWW service is stored in/SRV/WWW. /usr/bin is the directory for storing applications. /usr/share is the directory for storing shared data. /usr/lib is the directory for storing library files that cannot be run directly but are necessary for many programs to run. /usr/local: stores the upgrade package. /usr/share/doc: directory for storing system description files. /usr/share/man: directory for storing program description files. /var/log/message: directory for storing all login files. /var/spool/mail: Directory for storing emails. /var/run: The PID of a program or service is stored in this directory after it is started.

2. User directory

At /home/user, called the user’s working directory or home directory, represented as:

/home/user ~

Relative path and absolute path

Absolute path: Starts from /. The path described is absolute, for example, /home. Relative path: Starts from the current position. /.. /. And.. : It’s in every directory. And.. (View lS-a); . Indicates the current directory. . Indicates the upper level directory, that is, the parent directory. In the root directory. And.. Both represent the current directory

4. File permissions

File permissions are file access control permissions, which users and groups can access files and perform operations. Every file or directory in Unix/Linux contains access rights that determine who can access them and how.

<1> Access user

The access permission can be restricted in the following three ways: Allow only users to access (Owner) An owner is a user who creates files. A user is the owner of all files created by users. A user can allow the user group to access the files of the user. Users can be grouped into user groups. For example, all users of a certain type or project can be grouped into one user group by the system administrator. A user can grant file access permission to other members of the user group. Allow any user in the system to access (other users) Users also open their files to all users in the system, in which case all users in the system can access their directories or files. In this sense, all other users within the system are the Other user class.

<2> Access permission

A user can control the access to a given file or directory. A file or directory may have read, write, and execute permissions: Read permission (r) For a file, a user has the permission to read the contents of the file. For directories, you have permission to browse directories. Write permission (W) Permission to add or modify file contents. For a directory, it has the permission to delete or move files in the directory. Executable permission (x) For a file, the permission to execute the file; For directories, the user has permission to access directories. Note: Generally, Unix/Linux systems only allow file owners (owners) or superusers to change read and write permissions on files.

<3> Example Description: Usels -lhTo view

handy@ubuntu:~$ ls -ltotal 44 drwxr-xr-x 2 handy handy 4096 Aug 29 06:45 Desktop drwxr-xr-x 2 handy handy 4096 Aug 29 06:45 Documents drwxr-xr-x 2 handy handy 4096 Aug 29 06:45 Downloads -rw-r--r-- 1 handy handy 8980 Aug 29 06:39 examples.desktop drwxr-xr-x 2 handy handy 4096 Aug 29 06:45 Music drwxr-xr-x 2 handy handy 4096 Aug 29 06:45 Pictures drwxr-xr-x 2 handy handy 4096 Aug 29 06:45 Public drwxr-xr-x 2 handy handy 4096 Aug 29 06:45 Templates drwxr-xr-x 2 handy handy 4096 Aug 29 06:45 Videos handy@ubuntu:~$ls-LH Total 44K DRwxr-xr-x 2 Handy Handy 4.0K Aug 29 06:45 Desktop DRwxr-xr-x 2 Handy Handy 4.0K Aug 29 06:45 Documents DRwxr-XR-X 2 Handy Handy 4.0K Aug 29 06:45 Downloads - RW-r --r-- 1 Handy Handy 8.8K Aug 29 06:39 Examples. Desktop DRwxr-XR-x 2 Handy Handy 4.0K Aug 29 06:45 Music DRwxr-XR-x 2 Handy Handy 4.0K Aug 29 06:45 Pictures DRwxr-XR-x 2 Handy Handy 4.0K Aug 29 06:45 Public DRwxR-XR-x 2 Handy Handy 4.0K Aug 29 06:45 Templates Drwxr-xr-x 2 Handy Handy 4.0K Aug 29 06:45 Videos handy@ubuntu:~$Copy the code

Each user has its own read, write, and execute permissions. The first set of permissions controls access to your own files, the owner permissions. The second group of permissions controls access to files for one of the user groups. The third group of permissions controls the access of all other users to a user’s files. These three groups of permissions grant read, write, and execute permissions to different types of users (owners, user groups, and other users), forming a nine-type permission group.

3. Common basic commands

Linux provides a large number of commands, using it can effectively complete a large number of work, such as disk operation, file access, directory operation, process management, file permission setting, etc. There are more than 200 commands in the least number of Linux distributions. Here are only the most important and frequently used commands.

1. Command usage

Linux command format: command [-options] [parameter1]… Parameter description: Command: specifies the command name. [-options] : specifies an option for command control or optional parameter1… : Parameters passed to the command: can be zero one or more.

2. Check the help documentation

###<1>–help is the help information of the Linux command, for example, ls –help

<2>man

Man is a manual provided by Linux, which contains most of the instructions for commands and functions. The manual is divided into many sections. When using MAN, you can specify different sections to browse. Example: man ls; Man 2 Printf Man sections have the following meanings: 1: Standard commands 2: System calls 3: Library functions (e.g. Printf,fopen) 4: Library functions (e.g. Printf,fopen) File formats, such as Passwd, 6:Games and Toys 7:Miscellaneous, conventions and agreements, such as Linux File systems, network protocols, AND ASCII. Environ global variables (8: Administrative Commands, such as ifconfig) Man is searched in the order of the chapter number in the manual. Man sets the following function keys:

3. Automatic completion

When you type the first few letters of a command and press TAB, the system automatically completes the command for you

4. History commands

After the system has executed some commands, you can press up or down to view the previous commands. History lists the executed commands.

Common commands for file and disk management

<1> View the file information: ls

Ls is short for list. It lists the contents of a directory. It is one of the most common commands, similar to the dir command in DOS. Linux file or directory names can contain up to 265 characters, “. Represents the current directory, “..” Represents the upper level directory, with “. The file at the beginning of the file is hidden. You need to use the -a parameter to display the file.

<2> Output redirection command: >

Linux allows you to redirect the command execution results to a file, saving what should be displayed on the terminal to the specified file. Note: > output redirection overwrites the original content, >> output redirection is appended to the end of the file.

<3> Split screen display: more

In this case, you can run the more command to display only one page at a time. Press the space bar to display the next page, press q to exit the display, and press H to obtain help.

< 4 > pipe: |

Pipe: The output of one command can be piped as input to another command. Pipe we can understand the pipe in real life, to the end of the pipe plug things into, out the other end, “|” is divided into both ends around here, the left end plug (write), the right end take things (read).

<5> Clear screen: clear

The clear function is used to clear the display on the terminal (similar to the CLS screen clearing function of DOS). You can also use the shortcut key Ctrl + L (L is a letter).

<6> Switch working directory: CD

When using Unix/Linux, you often need to change the working directory. The CD command helps you change the working directory. Linux all directories and file names are case sensitive. CD can be followed by either an absolute path or a relative path. If the directory is omitted, the current user’s home directory is switched by default.

<7> Displays the current path: PWD

You can run the PWD command to display the current working directory. It is easy to enter the PWD command without parameters.

<8> Create directory: mkdir

You can create a new directory by using the mkdir command. The -p argument creates a directory recursively.

< complement > Create file: touch

Format: touch file name If the file does not exist, you can create a blank file. If the file exists, you can change the last modification date of the file.

<9> Delete directory: rmdir

You can delete a directory using the rmdir command. You must leave the directory and the directory must be empty; otherwise, the deletion fails.

<10> Delete the file: rm

You can use RM to delete files or directories. Be careful with the rm command because files cannot be recovered after being deleted. To prevent file deletion, you can use the -i parameter after rm to confirm the files to be deleted one by one.

-r

<11> Create a link file: ln

Linux link files are similar to shortcuts on Windows. Link files are classified into soft links (with -s) and hard links. Soft link: The soft link does not occupy disk space. If the source file is deleted, the soft link becomes invalid. Use an absolute path for the source file. Ln -s Source file link Hard link of a file: a hard link can only link to common files, but not to directories. It is equivalent to a small name of a file and is not used in daily use. A file is deleted only when the number of hard links of a file (viewed by using ls -l) is 0. Ln Source file Link file

In Linux, file data and file names are stored separately.

<12> View or merge file contents: cat

Concatenate is used to view file content (suitable for less content, use more), create files, merge files, and append file content.

There is also a nl command in Linux that is equivalent to the cat-b effect.

<13> Text search: grep

Grep command is a powerful text search tool in Linux system. Grep allows pattern search of text files. If a matching pattern is found, grep prints all the lines containing the pattern. The general format of grep is as follows: grep [- option] ‘Search content string’ File name When you enter string parameters in the grep command, you are advised to enclose them in quotation marks or double quotation marks. For example, grep ‘a’ 1.txt.

<14> Find a file: find

Find supports regular expression search of file names, search by file modification time, search by file size, search by file permission, search by file type, and so on. After finding files, you can directly run commands on the found files, which is very powerful.

The find command is typically written as follows: find finds the criteria for finding a path. For example, find /home/type d-ls, which means to find all directories under /home/and display detailed information about the directories.

Subsequent commands (actions found after) :

-print: displays. -ls: similar to ls-l-delete: delete matched lines -ok COMMAND {} \ : Each operation requires user confirmation, {} refers to the found file, is a placeholder, for (find, etc. Output a list of contents) loop each one; \ is the symbol indicating the end of the -exec command. -exec COMMAND {} \ : No confirmation is required for each operationCopy the code

<15> Copy the file: cp

The cp command is used to copy a file or directory to another file or directory, which is equivalent to the COPY command in DOS.

<16> Move file: mv

You can use the mv command to move or rename a file or directory.

<17> Archive management: tar

Data on a computer often needs to be backed up. Tar is the most common backup tool in Unix/Linux. This command can archive a series of files into a large file, or unfile files to recover data. Tar Use format tar [option] Package file name The tar command is special. The option can be preceded by a hyphen (-) or not.

  • File packaging:tar -cvf ***.tar 1.py 2.py 3.txt *.c
  • Unpacking files:tar -xvf ***.tar -C ~/Desktop

<18> File compression: gzip

Tar is used in combination with the gzip command to implement file packaging and compression. Tar files are packaged but not compressed. Gzip is used to compress tar files. Generally, the file name extension is XXXX.tar.gz. Gzip format: gzip [options] Compressed file common options: -d decompress, -r decompress all subdirectories tar this command does not have the function of compression, it is only a package command, but the tar command added an option (-z) can call gzip to implement a compression function, implement a package before compression process.

  • Compressed usage:Tar -zcvf Compressed package name File 1 File 2...-z: Specifies the compressed package format as file.tar.gz
  • Decompression usage:Tar -zxvf Compressed package nameUnzip to the specified directory: -c (uppercase “C”)

<19> File compression: bzip2

Tar is used with the bzip2 command to implement file packaging and compression (the same usage as gzip). Tar packages files but does not compress them. Use bzip2 to compress tar files. The extension of tar files is xxxx.tar.gz2. Adding an option (-j) to tar to call bzip2 implements a compression function, implementing a process of packaging before compression.

  • Compressed usage:Tar JCVF Compressed package name file... (tar jcvf bk.tar.bz2 *.c)
  • Decompression usage:Tar JXVF package name (tar JXVF bk.tar.bz2)

<20> Decompress the zip and unzip files

Zip compressed files do not need to specify an extension. The default extension is ZIP.

  • Compressed file:Zip [-r] Target file (no extension) source file
  • Unzip files:Unzip -d Indicates the decompressed directory file

<21> View the command location: which

Common commands for user and permission management

User is an important part of Unix/Linux system. User management includes the management of user and group accounts. In Unix/Linux, each system must have an account and have different permissions for different system resources, whether you log in to the system locally or remotely. The root account in Unix/Linux is used for system maintenance and management and has unrestricted access to all parts of the Unix/Linux operating system. During Unix/Linux installation, the system automatically creates many user accounts, and these default users are called “standard users”. On most VERSIONS of Unix/Linux, it is not recommended to log in to the system as user root.

<1> View the current user: whoami

The whoami command displays the name of the current account in the current system. You can run cat /etc/passwd to view system user information. A system administrator needs to log in to the system using multiple identities. For example, a common user logs in to the system and then runs the su command to switch to the root user for traditional management. At this point, you can use whoAMI to see the identity of the current user.

<2> View the login user: who

The who command is used to view information about all users who log in to the system.

<3> Exit the login account: exit

  • If the GUI is used, exit the current Terminal.
  • If you use SSH to log in remotely, log out of the account.
  • If you are the login user after switching, you will return to the previous login account when you quit.

<4> Switch users: su

You can run the su command to switch users. You can add – after su. The su – command differs from the su – command in that the su – command automatically converts the current working directory to the user’s home directory when switching to the corresponding user:

sudo
sudo

<5> Add or delete group accounts: groupadd and groupdel

Groupadd Group name Create a group account groupdel Group name Delete a group account cat /etc/group View user group information

<6> Modify the user group: usermod

  • Primary group: usually specified when creating a user/etc/passwdThe fourth column GID of the
  • Additional group: in/etc/groupThe last column represents the list of users for that group, which is used to specify additional permissions for users.usermodCan be used to set the userPrimary group/additional groupOn the ShellThe command format is as follows:

<7> Add user account: useradd

To add a user account in Unix/Linux, you can use the adduser or useradd commands, because the adduser command is a link to the useradd command, so the format of the two commands is exactly the same. The format of the useradd command is as follows: useradd [options and Parameters] Creates a user name

Note:

  • I forgot to add it when I created the user-mThe solution is:Delete the user and create it again(Don’t worry about setting permissions).
  • When a user is created, a group with the same name as the user is created by default.
  • User information is saved in/etc/passwdFile.
  • Use the defaultuseraddThe added user does not existsudoPermission, need to use the commandSudo usermod -g Sudo user name, add the user tosudoAdditional group.

<8> Set the user password to passwd

In Unix/Linux, a superuser can use the passwd command to set or change a password for a common user. You can also use this command to change your own password without using the user name.

<9> Delete the user: userdel

< complement > View the UID and GID: ID of the user

Command format: id User name

<10> Modify file permissions: chmod

Chmod File permissions can be changed in two formats: alphanumeric and numeric. Letters: chmod u/g/o/a +/-/= RWX file

The digital method

-R

<11> Modify file owner: chown

Format: chown username filename | directory name

<12> Change the file group to CHGRP

Ordered the lattice: the CHGRP group name file name | directory name

Notice that if you want to recursively modify it, you have to add -r.

Common commands for system and remote management

<1> View the current calendar: CAL

The CAL (calendar) command is used to view the current calendar. -y displays the calendar of the entire year.

<2> Displays or sets the time: date

Set the time format (administrator permission required) : date [MMDDhhmm[[CC]YY][.ss]] +format CC indicates the first two digits of YY. CC indicates the last two digits of YY, month, minute, day, hh, and second. Example: Date 010203042016.55. Display time format (date ‘+%y,%m,%d,%H,% m,% S’)

<3> View the process information: ps

Process is a program with certain independent function, it is the basic unit of operating system dynamic execution. You can run the ps (process status) command to view details about a process. The common options are as follows:

ps

<4> Dynamic display process: top

Using the top command, you can dynamically display the running processes. The top command can update the display information at a specified interval after running. You can use the top command with -d to specify the interval at which the display information is updated. After executing the top command, you can press the key to sort the displayed results:

<5> Terminate the process: kill

The kill command specifies the process id. It must be used together with ps. Format: kill [-signal] PID The pid signal value ranges from 0 to 15, where 9 indicates absolute termination. It can process processes that cannot be terminated by ordinary signals.

9 -

<6> Shutdown restart: reboot, shutdown, init

Shutdown Shutdown shutdown shutdown shutdown shutdown shutdown shutdown shutdown shutdown

  • Item is elected-rSaid,Restart the.
  • Item is elected-c“, the operation is cancelled.
  • If no option or parameter is specified, the computer will be shut down after one minute by default.
  • When maintaining a server remotely, it is best not to shut down the system, but to restart it. Common commands are as follows:

<7> Check the disk space: df

The df (disk free) command is used to check the disk space usage of a file system and display the usage of all file systems on nodes and disk blocks.

<8> Check the disk space occupied by the directory: du

The du (disk usage) command is used to measure the disk space occupied by directories or files. The result of this command is similar to that of df, but du focuses on disk usage. The format of the du command is du [option] Directory or file name

<9> View or configure nic information: ifconfig

If, we just type: ifconfig, it will display information for all network cards:

ifconfig | grep 'inet'
ensXX
127.0.0.1

<10> Test remote host connectivity: ping

Ping is used to check whether the network between the current computer and the target computer is normal. The higher the ping value is, the slower the speed is. Ping works in a similar way to sonar in a submarine. Ping is also commonly used as a verb among network administrators – ping computer X to see if it is still open.

Tip: In Linux, to terminate the execution of a terminal program, you can almost always use CTRL + C.

< supplement >SSH basics

Through the SSH client, you can connect to the remote machine where the SSH server is installed.

An SSH client is a program that connects to a remote computer using the Secure Shell (SSH) protocol. SSH prevents information leakage, prevents DNS spoofing and IP spoofing (encryption), and improves transmission speed (compression).

1) Domain name and port number

Domain name: a string of dot-separated names that are aliases of IP addresses for easy memorizing, for example, www.baidu.com. IP address: Find the computer on the network by IP address. Port number: Use the port number to find the application running on your computer.

The default port number of the SSH server is 22. If it is the default port number, you can omit it during connection.

2) Install and configure the SSH server

To install sSH-related services, run the following command: sudo apt-get install openssh-client openssh-server on the openssh-client server (delivered with Ubuntu).

  • In Ubuntu, you just need to installSSH server:sudo apt-get install openssh-server, start the serviceservice sshd startTo view the service status:service sshd statusTo set the login of the user with root permission, you should modify the configuration file:vi /etc/ssh/sshd_configThat is as follows:
# Authentication:
LoginGraceTime 120
PermitRootLogin yes
StrictModes yes
Copy the code

Then remember to restart the service: service SSHD restart, sudo /etc/init.d/ SSH stop, sudo /etc/init.d/ SSH start

You may need to: Turn off Ubuntu’s firewall:

sudo ufw disable # disable firewall

sudo ufw enable # enable firewall

sudo ufw status Check the firewall status
Copy the code

There are also possible errors: the user’s shell Settings in the /etc/passwd file are incorrect. (My previous error is here. The following figure is from checking the log in Ubuntu using service SSHD status.)

  • Openssh-server automatic startup on Ubuntu: Enable openssh-Server automatic startup on Ubuntu/etc/rc.localFile, before exit 0 statement:/etc/init.d/ssh start

3) Simple use of the SSH client

ssh [-p port] user@remote

  • userIs the user name on the remote machine. If not specified, it defaults to the current user.
  • remoteIs the address of the remote machineIPThe domain nameOr as we’ll see laterThe alias.
  • portisSSH ServerThe listening port, if not specified, is the default22.

Tip:

  • useexitLog out of the current user.
  • sshThis terminal command can only be used on Unix or Linux. On Windows, you need to install the client software.

4) Install and use the SSH client software in Windows

Tip: Download it from the official website. PuTTy:www.chiark.greenend.org.uk/~sgtatham/p… XShell:www.netsarang.com/download/ma…

5) SSH advanced use

Information about SSH configuration is stored in the user’s home directory.

Password-free login:

Configure aliases:

SSH -p port user@remote SSH -p port user@remote SSH -p port user@remote SSH /.ssh/config:

Host MAC HostName IP address User itheima Port 22Copy the code

SCP can also use the prompt: touch config after gedit config or vi config, and then can append.

< complement > Remote copy file: SCP

SCP stands for Secure Copy, which is a command to copy files remotely from Linux. The address format is basically the same as SSH, except that the port is specified with an uppercase -p.

# copy the 01.py file in the current local directory to Desktop/01.py in the remote home directory
If the path following: ':' is not an absolute path, the user's home directory is used as a reference path
scp -P port 01.py user@remote:Desktop/01.py

Copy the Desktop/01.py file in the remote home directory to 01.py in the current local directory
scp -P port user@remote:Desktop/01.py 01.py

# add the -r option to transfer folders
Copy the demo folder in the current directory to the Desktop in the remote home directory
scp -r demo user@remote:Desktop

Copy the Desktop in the remote home directory to the demo folder in the current directory
scp -r user@remote:Desktop demo
Copy the code

  • scpThis terminal command can only be used on Unix or Linux systems.
  • You can install PuTTy on a Windows operating systempscpCommand-line tool, or install FileZilla (Filezilla-project.org/) File transfer using FTP…
  • In addition to usingscpCommand copy, you can also use FTP service upload, install FTP service:sudo apt-get install vsftpd.
  • FTP service configuration:sudo vi /etc/vsftpd.confFind and modify the following information in the configuration file
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #### Usually use FileZilla only need to change ### write_enable=YES # upload files to FTP server!! # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # chroot_list_enable = YES # are not allowed to jump out of the home directory chroot_list_file = / etc/VSFTPD chroot_list # allow users in vsftpd.chroot_list to log in to FTP serverCopy the code

After changing the configuration file, run the service VSFTPD restart command to restart the VSFTPD service

To test the upload function, log in to the FTP server:
ftp IPUpload command to upload files to FTP server:
put somefileDownload command to download files from FTP server to local:
get somefileYou can also use FileZilla or Xftp with a graphical interface.

Delete or rename uploaded Garbled Chinese files ls -i: displays file inode numbers. An index node represents a file; Find-inum node number -delete: searches for and deletes the inum file that meets the specified inode number. The non-empty directory cannot be deleted. -inum node number -exec mv {} New name \ deleted: find./ -exec rm -rf {} \ {} is a placeholder for each file found. For each file, take a seat, wait for find to come out, and put it in the corresponding {} position. \ is the symbol indicating the end of the -exec command.

Common commands for Ubuntu software installation

<1> Install/uninstall software: apt

Apt, short for Advanced Packaging Tool, is a Linux installation package management tool that can install, uninstall, and update software packages on terminals.

<2> Configure the software source

If you want to install software faster in Ubuntu, you can set the image source and choose a server with faster Internet access to provide software download/installation services. Note: After replacing the server, you need a relatively long update process and need to wait patiently. After the update is complete, the re-installation software will be downloaded and installed from the newly configured server.

The so-called mirror source is the same content of all servers (mirror), but its location is different, domestic servers are generally faster.

Vi editor common commands

< 1 > vi introduction

You can use SSH to remotely log in to the server and quickly edit files using the visual interface (VI). Common files that need to be modified include source programs and configuration files, for example, SSH configuration files ~/. SSH /config

For editing files without a graphical interface, VI is the best choice! Every programmer working with Linux should learn some of vi’s common commands

In many Linux distributions, VI is directly used as a soft connection to VIm

vi

Vi, short for Visual Interface, is the core design idea of the most classic text editor VI in Linux — let the programmer’s finger always keep in the core area of the keyboard, can complete all the editing operations

Vi characteristics: no graphical interface powerful editor, can be to edit text content, not to typesetting, font, paragraph does not support the mouse operation, no menu, only the command, the vi editor in system management, server management Edit the file, its function is never a graphical interface editor can match.

vim

Vim is a text editor developed from VI. It supports code completion, compilation and error jump and other convenient programming functions are particularly rich. It is widely used in programmers and is known as the god of editors

<2> Open and create new files

$vi File nameCopy the code
  • If the file already exists, it will be opened directly
  • If the file does not exist, a new file is created

<3> Open the file and locate the lines

In daily work, you may open a file and locate the specified line. For example, when you know that a line of code has errors during development, you can quickly locate the error code. In this case, you can run the following command to open the file

$vi File name + line numberCopy the code

Tip: if you add a + without specifying a line number, it will go directly to the end of the file. If you do not add a +, it will go directly to the beginning of the file.

<4> Exception handling

If vi exits unexpectedly, swap files may be saved on disk

The next time you edit the file using vi, you will see the following screen information: Press d to delete the switch file, and the previous modification involved in abnormal exit will disappear.

Tip: When pressing the keyboard, note that the input method is in English state.

<5> Three working modes of VI

Vi has three basic working modes:

  • Command Mode To open a file, you need to enter the command mode using the vi interface to perform routine file editing operations, such as locating, turning pages, copying, pasting, and deleting files. In other graphics editors, actions performed by shortcut keys or mouse are performed in command mode

  • Last line mode – Perform operations such as save and exit. To exit vi and return to the console, you need to enter the command in the last line mode, which is the exit of VI

  • Edit mode – Normal text editing

    [image upload failed…(image-44394C-1551450393896)]

Tip: On Touch Bar Macs, pressing ESC is inconvenient. Use CTRL + [instead

Last-line mode command:

The command English function
w write save
q quit Exit, if not saved, not allowed to exit
q! quit Forced exit, exit without saving
wq write & quit Save and exit
x Save and exit

<6> Common commands

Command to learn the route diagram

  1. Repeat the command multiple times
    • In command mode, you can enter a number and then run the command repeatedly for a specified number of times
  2. Move and select (More practice)
    • viThe key to being fast isAbility to quickly locate lines of code to edit
    • The move command can be combined with the edit action command
  3. Edit operation
    • Delete, copy, paste, replace, indent
  4. Undo and repeat
  5. To find the replacement

1. Mobile (basic)

  • Be proficient in usingviFirst of all, we should learn how toCommand modeMove the cursor quickly
  • Edit action commands that can be used in conjunction with move commands
1) Up, down, left, right
The command function finger
h To the left The index finger
j down The index finger
k upward The middle finger
l To the right The ring finger

2) Inline movement
The command English function
w word Move one word back
b back Move one word forward
0 The beginning of a line
^ At the beginning of the line, the first position is not whitespace
$ End of each line
3) Row number movement
The command English function
gg go At the top of the file
G go The end of the file
Digital gg go Move to the number corresponding to the number of lines
Digital G go Move to the number corresponding to the number of lines
: digital Move to the number corresponding to the number of lines
4) Screen movement
The command English function
Ctrl + b back Page up
Ctrl + f forward Down the page
H Head The top of the screen
M Middle In the middle of the screen
L Low At the bottom of the screen

2. Move (program)

1) Paragraph movement
  • viUse blank lines to distinguish paragraphs in
  • In program development, it is common to have a piece of feature-related code written side-by-side — with no blank lines between them
The command function
{ On a
} The next leg of
2) Switch parentheses
  • In the world of programming,(a),[],{}It’s used a lot, andThey all come in pairs
The command function
% Parenthesis matching and switching
3) markers
  • During development, certain pieces of code may need to be addressed later, for example, editing, viewing
  • Use it firstmAdd a tag so that you canJump back quickly when neededorPerform other editing operations
  • Tag nameCan bea~zorA~ZAny betweenaThe letter
  • If the tagged line is deleted, the tagged line is also deleted
  • If a tag with the same name is added to another line, the tag that was previously added will be replaced
The command English function
mx mark Add the flag x, which is any letter from a to Z or between
‘x Locate directly to mark X

3. Select text (visual mode)

  • inviTo select text, you need to useVisualCommand switch toVisual model
  • viProvided in theThree kinds ofVisual mode, easy for programmers to chooseHow text is selected
  • According to theESCYou can drop it and go back toCommand mode
The command model function
v Visual model Select text in normal mode starting at cursor position
V Visual line mode Select the full row over which the cursor passes
Ctrl + v Visual block mode Select text vertically

Note: In visual mode, this can be used with the move command, for example: ggVG can select everything

4. Undo and Resume Undo

  • Before you learn the edit command, know how to undo a previous wrong edit action!
The command English function
u undo Undo last command
CTRL + r redo Undo undo command

5. Delete the text

The command English function
x cut Deletes the character where the cursor is located, or selects the text
D (Move command) delete Delete the contents of the move command
dd delete Delete the cursor line, can NDD copy multiple lines
D delete Delete to end of line

Tip: If a text is already selected in visual mode, you can remove the selected text with either D or X

  • The delete command can be used with the move command. The following are common combination commands: Dw # delete from cursor position to end of word d0 # Delete from cursor position to start of line D} # Delete from cursor position to end of paragraph NDD # Delete consecutively n lines of d code from cursor position down G # Delete all lines of code from cursor position to specified line d’a # Delete all code between the cursor line and tag A

Tip: You can use :set nu and :set nonu to set whether to display the line number.

6. Copy and paste

  • viOne is provided inA buffer of copied text
    • The copy command saves the selected text in a buffer
    • The text deleted by the delete command is saved in the buffer
    • Use the paste command to insert the text of the buffer into the position of the cursor where it is needed
The command English function
Y (move command) copy copy
yy copy Copy one row, you can nyY copy multiple rows
p paste paste

prompt

  • The commandd,xIt’s like a graphical interfaceThe shear actionCTRL + X
  • The commandyIt’s like a graphical interfaceCopy operationCTRL + C
  • The commandpIt’s like a graphical interfacePaste operationCTRL + V
  • viIn theThere is also only one text bufferIf you’ve done it laterCopy and cutOperation, the contents of the previous buffer are replaced

Pay attention to

  • viIn theText bufferAnd the system ofThe clipboardNot the same
  • So use it in other softwareCTRL + CCopy content that cannot be inviThrough thePPaste command
  • You can use the right mouse button to paste in edit mode

7. Replace

The command English function Working mode
r replace Replace current character Command mode
R replace Replaces the character after the current line cursor Replace mode
  • RCommand can enterReplace modeAfter the replacement is complete, pressESCYou can return toCommand mode
  • The purpose of the replace command is to make lightweight changes to the file without going into edit mode

8. Indent and repeat execution

The command function
>> Increase indentation to the right
<< Reduce indentation to the left
. Repeat the last command
  • Indentation commandWhen you’re developing your program,Uniformly increase the indentation of codeMore useful!
    • Adding four Spaces at a time to the selected code is called increasing indentation
    • Removing four Spaces at a time before selecting code is called indentation reduction
  • inVisual modelThe indent command only needs to be useda >or<

In programs, indentation is often used to indicate code ownership

  • The less space in front, the higher the level of the code
  • The more Spaces in front, the lower the code level

9. Look for

Conventional search

The command function
/str Find the STR
  • After the specified content is found, theNextFind the next location to appear:
    • n: Find the next one
    • N: Find the previous one
  • If you don’t want to see the highlight, you can just look for anything in a file that doesn’t exist
Quick word matching
The command function
* Find the word behind the current cursor
# Look forward to the word where the cursor is currently located
  • In development, with word fast matching, you can quickly see where else the word has been used

10. Find and replace

  • inviFind and replace commands are required inAt the end of the line modeperform
  • Memory command format:
:%s///g
Copy the code
1) Global replacement
  • Replace all occurrences of old text in the file at once
  • The command format is as follows:
:%s/ old text/new text /gCopy the code
2) Visual area replacement
  • Select the range of text you want to replace
  • The command format is as follows:
:s/ old text/new text /gCopy the code
3) Confirm the replacement
  • If you take the tailgtogcAt the time of substitution, there will be a hint!Recommended use!

C: Conform.

:%s/ old text/new text/GCCopy the code
  1. yyesreplace
  2. nnoDon’t replace
  3. aallReplace all
  4. qquitExit the replacement
  5. llastLast, and move the cursor to the top of the line
  6. ^EScroll down
  7. ^YScrolling up

11. Insert commands

  • inviIn addition to the commoniEnter theEdit modeIt also provides the following commands to enter the editing mode:
The command English function The commonly used
i insert Inserts text before the current character The commonly used
I insert Insert text at the beginning of the line The commonly used
a append Adds text after the current character
A append Add text at the end of the line The commonly used
o Inserts an empty row after the current row The commonly used
O Inserts an empty row before the current row The commonly used

[image upload failed…(image-d3e85B-1551450393896)]

To type capital letters quickly, use: shift.

Exercise 1 – Edit commands and numbers together
  • During development, you may encounter continuous inputNThe same character

There are easy ways to do this in Python, but other languages usually require typing yourself

  • Such as:* * * * * * * * * *10 consecutive asterisks

This can be done in command mode

  1. The input10Is repeated 10 times
  2. The inputiEnter theEdit mode
  3. The input*That is, repeated words
  4. Press theESCReturn to theCommand mode, after returningviYou can put the first2, 3,The two-step operation repeats10

Tip: In normal development, do not press numbers until you enter edit mode

Exercise 2 – Annotate multiple lines of code with visual blocks
  • In development, it is possible to add comments to multiple lines of code at once

In Python, to comment code, you add a # before the code

This can be done in command mode

  1. Move to the comment you want to addLine 1According to the^Come to the beginning of a line
  2. According to theCTRL + vEnter theVisual blockmodel
  3. usejSelect successive lines of code to add down
  4. The inputIEnter theEdit modeAnd, inThe beginning of a line insert, Note: Be sure to useI
  5. The input#That’s the comment notation
  6. Press theESCReturn to theCommand mode, after returningviFor each line of code that was previously selectedbeforeinsert#

12. Split screen command

  • Belong toviHigh level command — yesEdit and view multiple files simultaneously
Last-line command extension

The last line commands are mainly for file operations: save, exit, save & exit, search & replace, save, create, browse file

The command English function
:e . edit The built-in file browser opens to browse the files in the current directory
: n filename new The new file
The file name: w write Save as, but still edit the current file without switching files

Tip: Before switching files, ensure that the current file has been saved!

  • The last command you have learned:
The command English function
:w write save
:q quit Exit, if not saved, not allowed to exit
:q! quit Forced exit, exit without saving
:wq write & quit Save and exit
😡 Save and exit
:%s///gc Confirm search and replace

In real development, you can use the W command to back up code periodically

Split screen command
  • Using the split screen command, you can edit and view multiple files simultaneously
The command English function
:sp [filename] split Add split screen horizontally
: VSP [filename] vertical split Add split screen vertically
1) Switch to the split screen window

Split-screen Windows are based on the shortcut key CTRL + W, which corresponds to the English word window

The command English function
w window Switch to the next window
r reverse Swap window
c close Close the current window, but not the last window
q quit Exit the current window or, if it is the last window, close vi
o other Close other Windows
2) Resize the window

Split-screen Windows are based on the shortcut key CTRL + W, which corresponds to the English word window

The command English function
+ Increase window height
Reduce window height
> Increase window width
< Reduce window width
= Equal window size

The command to adjust the width and height of the window can be used with numbers, for example, 5 CTRL + W + to increase the height five times in a row

13. Quick view of common commands

vimrc
  • vimrcvimVim configuration file, you can set vim configuration, including:hotkey,The color,Syntax highlighting,The plug-in
  • LinuxvimrcI have two positions,The configuration file in the home directory has a higher priority
/etc/vim/vimrc
~/.vimrc
Copy the code
  • Common plug-ins are:
    • Code completion
    • Code folding,
    • search
    • Git integration
  • There are a lot of good guys on the Internet that have been configured forpythonThe development ofvimrcFiles can be downloaded and used directly, or moreLinuxMore familiar with, learn again!

Tips:

Font size changes in terminal: Zoom in is CTRL shift +, zoom out is CTRL -. Exit a program in the terminal: usually q, maybe CTRL C or CTRL D. Open a terminal as a new TAB: CTRL, Alt, T.

Full text mind mapping