preface

The importance of learning Linux for a programmer is self-evident. Front-end development has less exposure to Linux than back-end development, so it’s easy to overlook it. But learning it well is one of the essentials for programmers.

If this article can help you, please go to πŸ‘.

The author uses ali cloud server ECS (the cheapest kind) CentOS 7.7 64-bit. Of course, you can also install a virtual machine on your own computer, and then install CentOS in the VIRTUAL machine (this is completely free). As for its installation tutorial can go to Google search, related tutorials are numerous.

The Linux foundation

The operating system

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

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

What is a Linux

The difference between a Linux kernel and a Linux distribution

  • LinuxSystem kernel refers to byLinus TorvaldsResponsible for the maintenance of system core programs that provide hardware abstraction layer, hard disk and file system control and multitasking functions.
  • LinuxA distribution system is what we call itLinuxOperating system, that is, byLinuxKernel and a variety of common software products.

Conclusion: trueLinuxIt refers to the system kernel, and we often sayLinuxA complete release of an operating system with some basic software.

Linux contrast Windows

  1. Stable and efficient;
  2. Free (or for a small fee);
  3. Fewer loopholes and quick repair;
  4. Multi-task and multi-user;
  5. More secure user and file permission policies;
  6. Embedded systems suitable for small kernel programs;
  7. Relatively low cost of resources.

Linux System Types

  • Red Hat Enterprise editionLinux : RHELIt is the most widely used in the worldLinuxSystem. It has extremely high performance and stability, and is a (fee-based) system used in many production environments.
  • Fedora: A desktop suite released by Red Hat, which gives users free access to the latest technologies or tools that will be added as they matureRHELIn the system, soFedoraHas become aRHELExperimental version of the system.
  • CentOSBy:RHELThe system is recompiled and released to users for freeLinuxSystem, with a wide range of users.
  • Deepin: Released in China to integrate and configure excellent open source products.
  • Debian: Strong stability, security, provides free basic support, has a high recognition and utilization rate in foreign countries.
  • Ubuntu: is a derivative fromDebianOperating system, the new hardware has a strong compatibility.Ubuntu 与 FedoraThey are excellentLinuxDesktop system, andUbuntuIt can also be used in the server world.

The terminal is connected to ali Cloud server

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

  1. This black panel is the terminal which is the terminalShellCommand line environment.
  2. ssh root@xxxThis is an order. It has to be inShellTo be executed.

Shell

The word Shell originally means “Shell”, which corresponds to the kernel. It refers to the layer outside the kernel, which is the dialogue interface between the user and the kernel.

  • ShellIs a program that provides an environment for a conversation with the user. This environment has a single command prompt that allows the user to type commands from the keyboard, so it is also called the command line environment (command line interfaceFor short,CLI).ShellReceives the commands entered by the user, sends the commands to the operating system, and returns the results to the user.
  • ShellIs a command interpreter that interprets commands entered by the user. It supports variables, conditions, loops, etc., so users can use itShellCommand to write various small programs, also known asShellThe script. These scripts all passShellThe interpretation is executed without compilation.
  • ShellIs a toolkit that provides a variety of gadgets for users to easily use the functions of the operating system.

The types of the Shell

There are many kinds of shells, as long as the user can provide a command line environment program, can be regarded as a Shell.

Historically, the major shells have been the following:

  • 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.

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

The command

Command line prompt

After entering the command line environment, the user will see the Shell prompt. The prompt is usually a string of prefixes ending with a dollar sign, $, after which the user can type various commands.

Execute 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. The home directory of common users is /home.

  • # : indicates the permissions you have (# for root user, $for ordinary user).

  • 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 details in the following section. Here, use the root user first.

[Remarks] The root user is the super user and has all operating system permissions.

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 (all files + list display) Single long parameter: ls --all Multiple long parameters: ls --reverse --all Mixed long and short 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 start learning Linux commands, there are a few shortcuts that you must master in advance that will last your entire Linux career.

  • Use the up and down arrow keys ↑ and ↓ to retrieve past commandsLinuxCommand;
  • A command or parameter can be used only by entering the first few digitsTabKey completion;
  • Ctrl + R: used to find used commands (historyThe command is used to list all the commands that have been used before and enter them!Commands are numbered (! 2) can 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: cuts from cursor position to line head;
  • Ctrl + K: cuts from cursor position to end of line;
  • Ctrl + W: Cut a word to the left of the cursor;
  • Ctrl + Y: pasteCtrl + U | K | YA command to cut;
  • Ctrl + A: the cursor jumps to the beginning of the command line.
  • Ctrl + EThe cursor jumps to the end of the command line.
  • Ctrl + DClosed:ShellThe session;

Files and Directories

Organization of files

Check the path

pwd

Displays the path to 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 which command also exists in Linux.

Basically a command is an executable program.

Browse and switch directories

ls

Lists files and directories, one of the most commonly used commands in Linux.

【 Common parameters 】

  • -aShow all files and directories including hidden
  • -lDisplay detailed list
  • -hSuitable for human reading
  • -tSort files by the time they were last modified
  • -iDisplay fileinode ( inodeIs the identity of the file content.

cd

CD is short for change directory.

CD / --> Jump to root directory CD ~ --> jump to home directory CD.. --> Go to the upper directory CD./home --> Go to the home directory of the current directory CD /home/lion --> Go to the lion directory of the home directory of the root directory CD --> Go to the home directory without adding any parametersCopy the code

[Note] Entering CD /ho + TAB once will automatically complete the path + TAB twice will list all possible directories.

du

Example List directory size information.

【 Common parameters 】

  • -hSuitable for human reading;
  • -aAt the same time, the size information of files in the directory is listed.
  • -sOnly the total size is displayed, but no specific information is displayed.

Browse and create files

cat

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

cat cloud-init.log
Copy the code

【 Common parameters 】

  • -nDisplays the line number.

less

Pagination displays file contents, which is better for viewing large files.

less cloud-init.log
Copy the code

[Quick operation]

  • Space bar: forward a page (a screen);
  • bKey: Back a page;
  • Enter key: forward line;
  • yKey: back one line;
  • Up and down keys: Go back or forward a line.
  • dKey: forward half a page;
  • uKey: back half a page;
  • qKey: Stop reading file, abortlessCommand;
  • =Key: display the contents of the current page is the number of lines in the file and some other details about the contents of the page;
  • hKey: Display help document;
  • /Key: After entering the search mode, pressnKey to jump to a matching item, pressNThe key jumps to the previous match item and can also enter a regular expression match.

head

Display 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

Display 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
  • -fIt can also be used to check the file every second for updates-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 】

  • -pRecursively create a directory structuremkdir -p one/two/threeΒ 

Copy and move files

cp

Copy files and directories

Cp file file_copy --> file_copy --> cp file one --> cp file one --> File cp file one/file_copy --> copy file to one directory TXT folder --> Copy all TXT files in the current directory to the Folder directoryCopy 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 file files to directory one mv new_folder one --> Move the new_folder folder to directory one mv *. TXT folder --> Move all TXT files in the current directory Move the file to the Folder folder mv file new_file -> file rename the file to new_fileCopy the code

Delete and link files

rm

Delete files and directories. Because Linux does not have a recycle bin, it is difficult to recover files and directories after deletion. Therefore, exercise caution when performing this operation

Rm new_file --> Delete new_file file rm f1 f2 f3 --> Delete f1 F2 F3 at the same timeCopy the code

【 Common parameters 】

  • -iConfirm to the user whether to delete;
  • -fForcible file deletion;
  • -rRecursive delete folder, famous delete operationrm -rf 。

ln

Link: 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 name, file content, and permissions. The list of file names is stored elsewhere on the hard disk and the file content is stored separately. Each file name is bound to the file content through inode identification.

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, Therefore, soft links are more widely used.

Ln file1 file2 --> Create a hard link with file2 as file1Copy the code

If we delete file1 using rm file1, there is no effect on file2. For hard links, deleting files on either side does not remove the contents of the files that point to each other. Only after file1 and file2 are deleted will the contents of the file they point to disappear.

Soft links

Soft links are similar to shortcuts under Windows.

ln -s file1 file2
Copy the code

Run the ls -l name command to view details 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

File2 is just a shortcut to file1. It points to file1, so it shows the contents of file1, but the inode of File2 is different from that 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 to which it points is missing.

Users and Permissions

The user

Linux is a multi-user operating system. In Linux, we could theoretically create an infinite number of users, but these users are grouped into different groups. There is a special user named root, who is the superuser and has the highest privileges.

The user created by ourselves is a user with limited permissions, which greatly improves the security of the Linux system and effectively prevents misoperations or virus attacks. However, the sudo command can be used when some commands require higher permissions.

sudo

Run commands as root

Sudo date --> You don't need to use sudo to check the dateCopy the code

useradd + passwd

  • useraddAdding a New User
  • passwdChanging a User password

Both commands require root privileges

Useradd lion --> Add a lion user. After adding a lion user, you can view passwd lion --> change the password of the lion user in /homeCopy the code

userdel

To delete a user, you need the permission of user root

Userdel lion --> will delete only the user name, not the corresponding folder from /home userdel lion --> will delete the corresponding folder under /homeCopy the code

su

To switch users, you need the root user permission

Sudo su --> switch to user rootexitTo switch a common user to the root user, run the command or CTRL + D.) Su lion --> Switch to the common user su --> Switch to the root userCopy the code

Group Management

In Linux, every user belongs to a specific group. If you do not set a group for a user, by default a group with the same user name will be created and the user will be assigned to this group.

groupadd

To create a group, use the same method as useradd.

groupadd friends
Copy the code

groupdel

Example Delete an existing group

Groupdel foo --> Deletes group fooCopy the code

groups

View the group of the user

Groups Lion --> check the group where the lion user belongsCopy the code

usermod

Used to modify user accounts.

【 Common parameters 】

  • -lRename the user. One thing to note/homeThe name of the user’s home directory in the.
  • -gModify the group to which the 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 -GIt takes you out of the group, and if you don’t want to do that, you have to add it again-aParameter, meansappendAdditional meaning.

chgrp

Group used to modify files.

CHGRP bar file. TXT -> fileCopy the code

chown

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

Chown lion:bar file. TXT --> change file. TXT to lion and group to barCopy the code

【 Common parameters 】

  • -RRecursively set subdirectories and subfiles,chown -R lion:lion /home/frank 把 frankThe folder’s users and groups are changedlion 。

File Permission Management

chmod

Modify the access permission.

chmod 740 file.txt
Copy the code

【 Common parameters 】

  • -RFile access permissions can be modified recursively, for examplechmod -R 777 /home/lion

Modifying permissions is simple, but understanding their deeper meaning is more important. Let’s learn the file permissions of Linux systematically.

[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 of a file or directory. Let’s figure out what it means.

  • d: indicates a directory, that is, it is a directory, ordinary files are-, the link isl 。
  • r : readIndicates that the file is readable.
  • w : writeIndicates that a file can be written. If a file has the write permission, it can be deleted.
  • x : executeIndicates that the file is executable.
  • -: indicates that no corresponding permission is available.

The overall permissions are divided by users, as shown in the figure below:

Drwxr-xr-x

  • It’s a folder;
  • Its owner has read, write, and execute permissions.
  • Group users have read and execute permissions, but do not have write permissions.
  • Its other users have read and execute permissions, but no 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.

Number assignment permission
permissions digital
r 4
w 2
x 1

So to change permissions, just do some simple additions:

chmod 640 hello.c 

# analysis6 = 4 + 2 + 0 Indicates that the owner has the RW right. 4 = 4 + 0 + 0 Indicates that the group user has the R right. 0 = 0 + 0 + 0 indicates that other users have no rightsCopy the code
Use letters to assign permissions
  • u : userThe abbreviation for user stands for owner.
  • g : groupThe abbreviation of “group” stands for group users.
  • o : otherFor other users.
  • a : allThe abbreviation for “all” stands for all users.
  • +: plus indicates adding permission.
  • -: Minus sign indicates that the permission is removed.
  • =: Equals sign, indicating the permission assignment.
Chmod u+rx file --> Owner of file file Adds read and run permission. Chmod G +r file --> Group user of file file Adds read permission. Chmod o-r file --> Other user of file file Deletes read permission G +r o-r file --> Group user of file Add the read permission. Remove read permission from other users chmod go-r file --> File group of file and other users Remove read permission from other users chmod +x file --> File Add run permission to all users of file chmod u= RWX,g=r,o= -file --> The owner of file assigns read/write and execute permissions. Other users in the group assign read permissions. Other users have no permissionsCopy the code

Find files

locate

Search all files and directories that contain the keyword. The file name to be searched is followed by a regular expression.

Install the locate

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

[Note] The locate command will locate commands in the file database, not the full disk database. Therefore, the newly created file will not be updated to the database, so it cannot be found. You can run updatedb to update the database.

find

For finding files, it will go through your actual hard drive to find them, and it allows us to do follow-up with each file we find, which is very powerful.

Find < where > < what > < do >Copy the code
  • Where: Specifies which directory to look for, and all subdirectories of that directory will also be looked for.
  • What: What to look for, depending on the name of the file, its size, or its most recent access.
  • What to do: After the file is found, you can proceed. If this parameter is not specified,findThe command displays only the files found.

Search by filename

find -name "file.txt"--> Find. -name by name in the current directory and subdirectories"syslog"--> Search for files by name in the current directory and subdirectories"syslog"--> Syslog find /var/ on the entire hard disklog -name "syslog"--> In the specified directory /var/logFind /var/log -name "syslog*"Syslog1, syslog2... The wildcard character represents all find /var/ fileslog -name "*syslog*"--> Find the file that contains syslogCopy the code

The find command only looks for files that exactly fit the “What” string, whereas locate looks for all files that contain keywords.

Search by file size

Find /var-size +10M -> /var Find /var-size +1G Find /var-size +1G Find /var-size +1G Find /var-size +10M -> /var Find /var-size -> /var Find /var-size +1G Find /var-size +1G Find /var-size 1M --> /var Find /var-size 1M files in the /var directoryCopy the code

Search based on the last access time of the file

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

Find only directories or files

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

Operation search results

find -name "*.txt" -printf "%p - %u\n"--> Find all TXT files and print them in %p - %u\n format, where %p= file name and %u= file owner find-name"*.jpg"-delete --> Delete all files whose suffix is. JPG in the current directory and subdirectories. Therefore, use find-name with caution"*.c" -execchmod 600 {} \; --> For each.c ending file, proceed -execThe action specified by the parameter, {} will be replaced by the found file, \; Find-name is the required end"*.c"-ok chmod 600 {} \; --> And above functions, there will be a confirmation promptCopy the code

repositories

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

There is a repository for Linux packages, called software repository, which can be managed by using Yum, the default package management tool in CentOS, suitable for Red Hat. Can be understood as node.js NPM.

Yum common commands

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

Switch the CentOS software source

Sometimes the CentOS default YUM source is not necessarily the domestic mirror, resulting in the speed of yum online installation and update is not ideal. In this case, set the yum source as a domestic mirror site. The main open source mirror sites in China are netease and Aliyun.

D/centos-base. Repo /etc/yom.repos. D/centos-base

2. Download the yum source configuration file of Aliyun to /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 cache

yum makecache
Copy the code

Read the manual

Linux commands are too diverse to remember from memory, so it’s important to learn how to use manuals.

man

Install update MAN

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

Type of MAN Manual

  1. Executable program orShellCommand;
  2. System call (LinuxKernel-provided functions);
  3. Library calls (functions in libraries);
  4. Documents (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 usedrootUser use);
  9. Internal nuclear program.

Man + number + command

Enter man + number + command/function to view 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 in the third part of the manual man ls --> find the ls usage manualCopy the code

Core area analysis of man manual :(taking 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 # include all arguments 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 is similar to the Xinhua dictionary to query the detailed information of a command or function, 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.

summary

Learning Linux knowledge not only makes it easy for the front end to deploy its own services, but also most of the commands here are common on MacOS, greatly improving our usual development efficiency.