Note: The explanation of Linux commands in this lesson is based on a Linux distribution named CentOS. I used an Alibaba Cloud server, and the system version was CentOS Linux release 7.6.1810. Different Linux distributions have some small differences in shell commands and utility programs, but these differences are very small.
A computer system with hardware only and no software is called a "bare machine". It is hard for us to use a bare machine to do daily computer work such as storage and computing, so we must use special software to control the hardware. The software closest to computer hardware is system software, and the most important part of that is the operating system. An operating system is a collection of programs that controls and manages all computer hardware and software resources, carries out resource allocation and task scheduling, and provides interfaces and an environment for system users and other software.
In the early days, before operating systems existed, people first loaded a program paper tape or card into the computer, then started the input device to send the program into the computer, and then started the program by using the switches on the console. When the program finished running, the printer printed the result, and the user unloaded the paper tape or cards and took them away. Then the second user used the computer and repeated the same steps. During the whole process, the user used the machine alone, the CPU waited for manual operation, and resource usage was very low.
First, start a supervisory program on the computer. Under the control of this supervisory program, the computer can automatically and in batches process one or more users' jobs. After one batch of jobs is finished, the supervisory program reads jobs again from the input device and stores them in the tape drive. Then it repeats the same steps to process tasks. The supervisory program keeps processing jobs and makes automatic job handoff happen, which reduces job setup time and manual operation time, and improves the use of computer resources. Batch systems can be divided into single-program batch systems, multiprogram batch systems, online batch systems, and offline batch systems.
A time-sharing system divides the processor running time into very short time slices, and gives the processor to each online job in turn according to the time slice. If a job cannot finish its computation within its time slice, the job is paused for a while, the processor is given to another job, and the original job waits for the next scheduling round to continue running. Because the computer is fast and jobs take turns very quickly, each user feels that they have one computer to themselves. Each user can send different operation control commands to the system through their own terminal, and finish tasks in a full human-computer interactive environment. To solve the problem that time-sharing systems could not respond to user commands in time, real-time systems appeared. These systems can finish event processing within a strict time range and respond in time to random outside events.
-
In the 1960s, IBM's System/360 series had a unified operating system called OS/360.
-
In 1965, AT&T's Bell Labs joined GE and MIT in the MULTICS project.
-
In 1969, the MULTICS project failed. Ken Thompson was staying at home, and for playing the game Space Travel, he used assembly language to develop Unics on the already outdated PDP-7.
Note: It is hard to imagine that such a great operating system as Unix was developed by a programmer staying at home, on an outdated machine, just for playing a game.
-
In 1970 and 1971, Ken Thompson and Dennis Ritchie rewrote Unics in the B language on the PDP-11, and at Brian Kernighan's suggestion renamed it Unix.
-
In 1972 and 1973, Dennis Ritchie invented the C language to replace the less portable B language and began rewriting Unix in C.
-
In 1974, Unix released the milestone Version 5, which was almost entirely implemented in C.
-
In 1979, starting from Unix Version 7, AT&T privatized Unix through new licensing terms.
-
In 1987, Professor Andrew S. Tanenbaum wanted to explain the details of operating-system internals to students in class, so to avoid copyright disputes, he decided to develop a Unix-compatible operating system himself without using any AT&T source code. This system was named Minix.
-
In 1991, while Linus Torvalds was studying at the University of Helsinki in Finland, he tried to do some development work on Minix. But because Minix was only an operating system for teaching and was not very powerful, Linus wrote a disk driver and file system so that he could more easily read, write, and download files in the university's newsgroup and mail system. These things formed the early shape of the Linux system kernel.
The picture below is the map of the Unix operating-system family.
Linux is a general-purpose operating system. An operating system is responsible for task scheduling, memory allocation, and handling peripheral device I/O. An operating system is usually made up of two parts: the kernel (the core program that runs other programs and manages hardware devices such as disks and printers) and system programs (device drivers, low-level libraries, shell, service programs, and so on).
The Linux kernel was developed by Linus Torvalds and was released in September 1991. As a product of the internet age, the Linux operating system was developed together by many developers around the world, and it is a free operating system. Note that freedom and free of charge are not the same idea.
- It is a general-purpose operating system and is not tied to specific hardware.
- It is written in C, has strong portability, and has kernel programming interfaces.
- It supports multiple users and multiple tasks, and supports a safe layered file system.
- It has many practical programs, complete network functions, and strong support documents.
- It has reliable security and good stability, and is more friendly to developers.
Linux commands in Linux systems usually use the format shown below.
command [named options] [target]-
Get login information:
w/who/last/lastb[root ~]# w 23:31:16 up 12:16, 2 users, load average: 0.00, 0.01, 0.05 USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT root pts/0 182.139.66.250 23:03 4.00s 0.02s 0.00s w jackfrue pts/1 182.139.66.250 23:26 3:56 0.00s 0.00s -bash [root ~]# who root pts/0 2018-04-12 23:03 (182.139.66.250) jackfrued pts/1 2018-04-12 23:26 (182.139.66.250) [root ~]# last root pts/0 117.136.63.184 Sun May 26 18:57 still logged in reboot system boot 3.10.0-957.10.1. Mon May 27 02:52 - 19:10 (-7:-42) ...
-
Check the shell you are using:
psA shell is also called a shell program. It is the translator between the user and the operating-system kernel. Put simply, it is the interface for interaction between people and the computer. In many Linux systems, the default shell is
bash(Bourne Again SHell), because it can use the Tab key to complete commands and paths, can save command history, can conveniently configure environment variables, and can execute batch operations. -
View the description and location of a command:
whatis/which/whereis[root ~]# whatis ps ps (1) - report a snapshot of the current processes. [root ~]# whereis ps ps: /usr/bin/ps /usr/share/man/man1/ps.1.gz [root ~]# which python /usr/bin/python
-
Clear what is shown on the screen:
clear -
View help documents:
man/info/--help/apropos[root@izwz97tbgo9lkabnat2lo8z ~]# ps --help Usage: ps [options] ... [root@izwz97tbgo9lkabnat2lo8z ~]# man ps PS(1) User Commands PS(1) NAME ps - report a snapshot of the current processes. ...
-
View the system and host name:
uname/hostname[root@izwz97tbgo9lkabnat2lo8z ~]# uname Linux [root@izwz97tbgo9lkabnat2lo8z ~]# hostname izwz97tbgo9lkabnat2lo8z [root@iZwz97tbgo9lkabnat2lo8Z ~]# cat /etc/centos-release CentOS Linux release 7.6.1810 (Core)
-
Time and date:
date/cal[root@iZwz97tbgo9lkabnat2lo8Z ~]# date Wed Jun 20 12:53:19 CST 2018 [root@iZwz97tbgo9lkabnat2lo8Z ~]# cal June 2018 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 ...
-
Restart and shut down:
reboot/shutdown[root ~]# shutdown -h +5 Shutdown scheduled for Sun 2019-05-26 19:34:27 CST, use 'shutdown -c' to cancel. ... [root ~]# shutdown -r 23:58 Shutdown scheduled for Sun 2019-05-26 23:58:00 CST, use 'shutdown -c' to cancel.
-
Exit login:
exit/logout -
View command history:
history
[root@iZwz97tbgo9lkabnat2lo8Z ~]# history
...
452 ls
453 cd Python-3.6.5/
454 clear
455 history
[root@iZwz97tbgo9lkabnat2lo8Z ~]# !454-
Create and delete empty directories:
mkdir/rmdir -
Create and delete files:
touch/rmtouchis used to create an empty file or change file times. In Linux, a file has three times:- time when content is changed:
mtime - time when permissions are changed:
ctime - last access time:
atime
- time when content is changed:
- Important options of
rm:-i: interactive delete. It asks about every item.-r: delete directories and recursively delete files and directories in them.-f: force delete. Ignore files that do not exist and show no prompt.
-
Switch and view the current working directory:
cd/pwdNote: The
cdcommand can be followed by a relative path (using the current path as the reference) or an absolute path (starting with/) to switch to the specified directory. You can also usecd ..to go back to the upper-level directory. -
View directory contents:
ls-l: view files and directories in long format-a: show files and directories that start with a dot (hidden files)-R: when there is a directory, keep expanding it recursively-d: list only directories, not other content-S/-t: sort by size / time
-
View file content:
cat/tac/head/tail/more/less/rev/odNote: The command
wgetis used above. It is a network downloader program that can download resources from a specified URL. -
Copy and move files:
cp/mv -
Rename files:
rename -
Find files and search content:
find/grepNote:
grepcan use regular expressions when it searches strings. If you need regular expressions, you can usegrep -Eor directly useegrep. -
Create links and view links:
ln/readlink[root@iZwz97tbgo9lkabnat2lo8Z ~]# ls -l sohu.html -rw-r--r-- 1 root root 212131 Jun 20 19:15 sohu.html [root@iZwz97tbgo9lkabnat2lo8Z ~]# ln -s /etc/centos-release sysinfo [root@iZwz97tbgo9lkabnat2lo8Z ~]# cat sysinfo CentOS Linux release 7.4.1708 (Core)
Note: Links can be divided into hard links and soft links (symbolic links). A hard link can be thought of as a pointer to file data, like the reference count of an object in Python. Each time one hard link is added, the file's link count increases by 1. Only when the link count becomes 0 can the storage space of that file possibly be covered by other files. When we usually delete a file, we are not really deleting the data on the hard disk. We only delete a pointer, or we can say one usage record of the data. A soft link is similar to a shortcut in Windows. When the file linked by the soft link is deleted, the soft link also becomes invalid.
-
Compress and decompress, and archive and unarchive:
gzip/gunzip/xz
[root@iZwz97tbgo9lkabnat2lo8Z ~]# wget http://download.redis.io/releases/redis-4.0.10.tar.gz
...
[root@iZwz97tbgo9lkabnat2lo8Z ~]# gunzip redis-4.0.10.tar.gz
[root@iZwz97tbgo9lkabnat2lo8Z ~]# ls redis*
redis-4.0.10.tar- Archive and unarchive:
tar
[root@iZwz97tbgo9lkabnat2lo8Z ~]# tar -xvf redis-4.0.10.tar
redis-4.0.10/
redis-4.0.10/.gitignore
...Note: Both archiving (also called creating an archive) and unarchiving use the
tarcommand. Usually, creating an archive needs the three options-cvf. Here,cmeans create,vmeans show verbose details, andfmeans the file of the archive. Unarchiving needs-xvf, wherexmeans extract, and the other two options are the same as for creating an archive.
- Turn standard input into command-line arguments:
xargs
This command is often used in pipes and redirection.
- Show the file name or directory name in a path:
basename/dirname - Other related tools:
sort: sort contentuniq: remove adjacent duplicatestr: replace specified content with new contentcut/paste: cut and paste content columnssplit: split filesfile: determine file typewc: count lines, words, and bytesiconv: convert encodings
[root ~]# cat foo.txt
grape
apple
pitaya
[root ~]# cat bar.txt
100
200
300
400
[root ~]# paste foo.txt bar.txt
grape 100
apple 200
pitaya 300
400
...-
Using a pipe,
|Example: count the number of files under the current directory.
find ./ | wc -lExample: list files and directories under the current path and add a number to each item.
ls | cat -nExample: count records in
record.logthat containAAAbut do not containBBB.cat record.log | grep AAA | grep -v BBB | wc -l
-
Output and error redirection:
>/>>/2> -
Input redirection:
< -
Multiple redirection:
teeThe following command both shows the result of
lson the terminal and appends it tols.txt.ls | tee -a ls.txt
aliasunalias
Aliases are convenient for mapping commonly used command combinations to short names.
[root ~]# alias ll='ls -l'
[root ~]# alias frm='rm -rf'
[root ~]# unalias frm-
Stream editor:
sedsedis a tool for operating on, filtering, and transforming text. It can append lines, insert lines, delete lines, and do substitutions. Like many commands shown earlier, it does not modify the original file unless you explicitly redirect or save the result.[root ~]# cat -n fruit.txt 1 banana 2 grape 3 apple 4 watermelon 5 orange [root ~]# sed '2a pitaya' fruit.txt banana grape pitaya apple watermelon orange
-
Pattern scanning and processing language:
awkawkis both a programming language and one of the most powerful text-processing tools in Linux. It can extract specific columns from text, use regular expressions to retrieve content, display specified rows, and perform statistics and calculations. In short, it is extremely powerful.[root ~]# cat fruit2.txt 1 banana 120 2 grape 500 3 apple 1230 4 watermelon 80 5 orange 400 [root ~]# awk 'NR==3' fruit2.txt 3 apple 1230 [root ~]# awk '{print $2}' fruit2.txt banana grape apple watermelon orange
-
Create and delete users:
useradd/userdel-d: specify the user's home directory when creating a user-g: specify the user's primary group when creating a user
-
Create and delete user groups:
groupadd/groupdelNote: User groups mainly exist to make it easier to manage a set of users together.
-
Change passwords:
passwdNote: If
passwdis used without specifying a target, it changes the current user's password. If you need to modify many users' passwords in bulk, you can usechpasswd.-l/-u: lock or unlock a user-d: clear a user's password-e: force the password to expire immediately, so the user must change it at login-i: disable the user some number of days after password expiration
-
View and modify password validity periods:
chage -
Switch users:
su -
Execute commands as an administrator:
sudoNote: If a user is expected to run commands with administrator privileges, that user must appear in the
sudoerslist. Thesudoersfile lives under/etc. -
Edit the
sudoersfile:visudo -
Display user and group information:
id -
Send messages to other users:
write/wall -
View or set whether you accept messages from other users:
mesg
- Naming rules: the maximum file-name length depends on the file-system type, but generally a file name should not exceed 255 characters. Although most characters can be used in file names, it is best to stick to upper- and lower-case English letters, digits, underscores, and periods. File names can contain spaces, but it is better to avoid them, because then you need either quotes or escaping.
- Extensions: file extensions are optional in Linux, but they help us understand file contents. Some applications recognize files by their extensions, but many do not. Commands such as
filedo not rely on extensions. - Hidden files: files whose names begin with a dot are hidden files in Linux.
/bin- binary files for basic commands/boot- static files for the boot loader/dev- device files/etc- configuration files/home- parent directory for ordinary users' home directories/lib- shared library files/lib64- shared 64-bit library files/lost+found- stores unlinked files/media- mount points for automatically detected devices/mnt- temporary mount points/opt- installation location for optional add-on packages/proc- kernel and process information/root- the home directory of the superuser/run- runtime data required by the system/sbin- binaries for the superuser/sys- a pseudo file system for devices/tmp- temporary files/usr- user applications/var- variable data
-
chmod- change file mode bitsNote:
chmodcan change permissions in two ways: symbolic notation and numeric notation. Besideschmod,umaskcan be used to specify which permission bits will be removed from the default permissions of new files. -
chown- change file owner -
chgrp- change group ownership
- List file-system disk-usage status:
df - Disk partition-table operations:
fdisk - Disk partitioning tool:
parted - Format a file system:
mkfs - File-system checking:
fsck - Convert or copy files:
dd - Mount and unmount:
mount/umount - Create, activate, and disable swap partitions:
mkswap/swapon/swapoff
Note: Running the commands above carries some risk. If you do not understand them clearly, do not use them casually. When using them, it is best to follow reference materials carefully and confirm whether you really intend to perform the operation.
-
Start
vim. You can launch it with eitherviorvim. A file name can be specified at launch, or you can name the file when saving. -
Command mode, insert mode, and last-line mode.
vimstarts in command mode. Pressingienters insert mode. PressingEscreturns to command mode. Entering:from command mode enters last-line mode, whereq!forces quit without saving. In command mode,venters visual mode, where a region can be selected and operated on. -
Save and quit:
:wq,q!,ZZ,:w -
Cursor operations
h,j,k,lCtrl+y,Ctrl+eCtrl+f,Ctrl+bG,gg, and numeric line jumps
-
Text operations
- delete:
dd,d$,d0,dw,:%d - copy and paste:
yy,p - undo and redo:
u,Ctrl+r - sort content:
%!sort
- delete:
-
Search and replace
- searching with
/ - replacing with commands such as
:1,$s/doc.*/hello/gice
- searching with
-
Settings in last-line mode
set ts=4set nu/set nonusyntax on/syntax offset rulerset hls/set nohls
Note: If you want these settings to take effect every time
vimstarts, write them to.vimrcin the user's home directory. -
Advanced tricks
- compare multiple files:
vim -d foo.txt bar.txt - open multiple files
- split windows with
sporvs - map shortcut keys with
maporinoremap - record and replay macros with
q, registers, and@
- compare multiple files:
yum, Yellowdog Updater Modifiedyum searchyum list installedyum installyum removeyum updateyum check-updateyum info
rpm, Red Hat Package Manager- install packages:
rpm -ivh <packagename>.rpm - remove packages:
rpm -e <packagename> - query packages:
rpm -qa
- install packages:
The lesson uses Nginx as an example of installation through yum, and MySQL as an example of installing RPM packages manually. It also notes that MySQL and MariaDB have conflicting lower-level dependencies, which is why some MariaDB libraries may need to be removed first.
The lesson uses MongoDB as an example here. The rough process is to download the package, extract it, add its bin directory to PATH, reload the shell configuration, and then verify the installed binaries with version commands.
- Installing Python 3.6
- Installing Redis 3.2.12
Note: After installing software such as Python, it is often still necessary to update
PATH, either in.bash_profileunder the user's home directory or in/etc/profile. The former behaves like a user-level environment variable, while the latter acts like a system-wide environment variable.
Under Linux we can install and configure many kinds of services, turning the system into a database server, web server, cache server, file server, message-queue server, and so on. Most Linux services are configured as daemons, background processes that continue to run without preventing Linux from shutting down cleanly. That is why many service names end with the letter d, short for daemon, such as firewalld, mysqld, and httpd. After a service is installed, it can usually be started, stopped, and otherwise managed with systemctl or service.
Examples from the lesson:
- Start the firewall service:
systemctl start firewalld - Stop the firewall service:
systemctl stop firewalld - Restart the firewall service:
systemctl restart firewalld - View firewall status:
systemctl status firewalld - Enable or disable the firewall at boot:
systemctl enable firewalld/systemctl disable firewalld
-
Execute commands at a specified time
at: queue a task to run at a specified timeatq: view the pending task queueatrm: remove a queued task
-
Crontab task scheduling
crontab -eopens the crontab for editing and lets you configure scheduled jobs with Cron expressions. The lesson also points out that related cron files live under/etc, and the systemcrontabfile itself includes comments explaining the Cron fields.
- Secure remote connection:
ssh - Fetch resources over the network:
wget - Send and receive mail:
mail - Older network configuration tool:
ifconfig - Newer network configuration tool:
ip - Network reachability checks:
ping - Display or manage route tables:
route - View network services and ports:
netstat/ss - Capture and inspect traffic:
tcpdump - Secure file copy:
scp - File synchronization:
rsync - Secure file transfer:
sftp
- View processes:
ps - Display the process tree:
pstree - Find processes matching given conditions:
pgrep - Terminate a process by PID:
kill - Terminate a process by name:
killall/pkill - Put a process in the background
Ctrl+Z&
- Query background jobs:
jobs - Continue a stopped job in the background:
bg - Bring a background job to the foreground:
fg - Adjust runtime priority:
nice/renice - Keep a process running after logout:
nohup - Trace system calls:
strace - View the current runlevel:
runlevel - Monitor resource usage in real time:
top
- Diagnose startup issues:
dmesg - View system activity information:
sar - View memory usage:
free - Virtual-memory statistics:
vmstat - CPU statistics:
mpstat - View a process's memory map:
pmap - Report device CPU and I/O statistics:
iostat - Display all PCI devices:
lspci - Display the status of inter-process communication facilities:
ipcs
As mentioned earlier, the shell is the application that connects the user and the operating system. It provides the interface for human-computer interaction. Shell scripts are programs written for the shell. We can use them for system management and file operations. In short, writing shell scripts is a basic skill for anyone who uses Linux seriously.
The internet contains a great deal of shell-scripting material, so this lesson does not attempt a complete treatment. Instead, it gives several small examples:
- Read two integers,
mandn, and calculate the sum of all integers frommton. - Automatically create a folder and a specified number of files.
- Automatically install a specified version of Redis.
-
Common Linux command-line shortcuts
Shortcut Description tabautocomplete a command or path Ctrl+amove the cursor to the start of the line Ctrl+emove the cursor to the end of the line Ctrl+fmove the cursor one character to the right Ctrl+bmove the cursor one character to the left Ctrl+kcut from the cursor to the end of the line Ctrl+ucut from the cursor to the beginning of the line Ctrl+wcut the word before the cursor Ctrl+ypaste the previously cut content Ctrl+cinterrupt the currently running task Ctrl+hdelete the character before the cursor Ctrl+dexit the current shell Ctrl+rsearch command history Ctrl+gexit history search Ctrl+lclear the screen and open a new line at the top Ctrl+slock the terminal temporarily Ctrl+qunlock the terminal Ctrl+zstop the current task and put it in the background !!execute the previous command !numberexecute the history command with that number !letterexecute the most recent command starting with that letter !$/Esc+.retrieve the last argument of the previous command Esc+bmove to the beginning of the current word Esc+fmove to the end of the current word -
What the sections of a
manpage meanSection Description NAMEthe command's name and short introduction SYNOPSISthe basic syntax of the command DESCRIPTIONa detailed description of the command and its options OPTIONSexplanations of command-line options EXAMPLESreference usage examples EXIT STATUSexit codes; typically 0means successSEE ALSOother related commands or information BUGSknown issues related to the command AUTHORinformation about the author

