Linux Study Notes

Linux, formally known as GNU/Linux, is a Unix-like operating system that is free to use and freely distributed.

Contents

Linux

Using Vim

  1. yy Copy the current line (copy 5 lines: 5yy)

  2. dd Delete the current line (delete 5 lines: 5dd)

  3. u Undo

  4. p Paste

  5. /text Search for the text "text" and highlight it

    After pressing Enter to enter search mode, press n to find the next occurrence.

    Shift + N Find the previous occurrence.

    :nohl Clear highlighting.

  6. :set nu / :set noun Show/hide line numbers

    1. gg/G / nG Quickly jump to the first line / last line / line n

System Operations

shutdown -h now		# 关机
halt 				# 关机
shutdown -h 1   	# 1分钟后关机
shutdown         	# 默认一分钟后关机
shutdown -r  now 	# 重启
reboot  			# 重启
sync			 	# 将内存中的数据写到硬盘,默认关机重启会执行

User Management

Concept of groups: Placing multiple users in the same group allows permissions to be managed for the group as a whole, making management more convenient.

When a user is not added to any group, the system creates a group with the same name as the user by default.

​

  1. useradd username Add a user
  2. useradd -d directory_name username Add a user and specify the user’s directory
  3. useradd -g group_name username Create a user and add them to the specified group
  4. passwd username Change the password for the specified user. If no username is specified, the current user’s password is changed.
  5. su username Switch to the specified user
  6. su - username Switch to the specified user (along with their environment)
  7. userdel username Delete a user
  8. userdel -r username Delete the specified user and their leftover files
  9. id username View information about the user (last login time and corresponding IP, groups the user belongs to, and user ID)
  10. who am i View the user who first logged in to the current session
  11. groupadd group_name Add a group
  12. groupdel group_name Delete an existing group
  13. usermod -g group_name username Add a user to a group

System Runlevels

  1. There are 7 runlevels:
    1. 0 Shutdown
    2. 1 Single-user mode, no network
    3. 2 Multi-user mode, no network
    4. 3 Multi-user mode with networking
    5. 4 Reserved by the system
    6. 5 Graphical interface
    7. 6 Reboot
  2. Single-user mode is commonly used to change the root password.
  3. init 0 Switch to system runlevel 0
  4. systemctl get-default Get the current runlevel
  5. systemctl set-default graphical.target Set the default runlevel to graphical mode
    1. multi-user.target Multi-user runlevel with networking

File Operations

  1. cd Directory operations
  2. touch Create an empty file
  3. rmdir Delete a directory; it must be empty for deletion to succeed.
  4. mkdir Create a directory. The -p option indicates parent directories; it also creates parent directories if they do not exist.
  5. rm The -r option recursively deletes directories. The -f option means “force” and does not prompt for confirmation.
  6. pwd Display the current path
  7. cp Copy files or directories. \cp does not prompt before overwriting. cp -r copies an entire directory recursively.
  8. mv Move/rename
  9. tail -f filename Follow a file and display updates; commonly used to view logs.
  10. more Scroll through file contents
  11. less Scroll through file contents without loading the entire file into memory; suitable for opening large files.
  12. cat View
  13. echo Output. echo $environment_variable_name outputs the value of an environment variable.
  14. > Output redirection (overwrite); >> output redirection (append)
  15. history Command history. history 10 displays the 10 most recent entries.
  16. date Date: "+%Y-%m-%d %H:%M:%S"
  17. cal Calendar. cal 2023 displays the calendar for all of 2023.
  18. find Search path; command for finding files. -name searches by filename; -user searches by owner; -size searches by file size (k, M, G). + and - indicate greater than and less than; without either, the size must match exactly.
  19. locate Search by index. It is faster, but the index must be created in advance. updatedb updates the index.
  20. which View the location of a command

Permission Operations

File identifiers: - file; d directory; c character device (various hardware); b block device (hard drive)

Identifier File Directory
r (4) Readable Can view contents with ls
w (2) Writable Can modify the directory’s contents (delete or add files)
x (1) Executable Can enter the directory with cd
  1. chown user filename Change the file owner. -r applies recursively.

    1. chown user:group filename Change the file owner and group
  2. chgrp group_name filename Change the file’s group. -r applies recursively.

  3. chmod permissions file Permission syntax

    1. u owner, g owning group, o others, a all. chmod u=rwx,g=rx,o=rx file
    2. u+w and u-w add or remove permissions for the owner. chmod u+w file
    3. Numeric permissions: r=4, w=2, x=1. chmod 777 file

Scheduled Tasks

crontab -e Edit the task list

​ Task format: * * * * *

​ Representing, respectively: minute, hour, day, month, weekday

​ Example: */1 * * * * Run once every minute

​ Special characters: / means every; , and - specify ranges

at A one-time scheduled task

atrm number Delete a scheduled task

Disk Operations

  1. lsblk List block device information. The -f option displays filesystem information.
  2. df Display disk information and usage. -h displays it in a more readable format.
  3. du Display disk usage for files in a specified directory. -h uses more readable units; --max-depth=1 sets the subdirectory depth; -a includes files.
  4. fdisk /dev/sda Operate on and partition the specified block device.
  5. mkfs Create a filesystem
  6. mount block_device_partition mount_directory Mount a device outside the Linux system (temporary mount; lost on reboot)
  7. umount Unmount a device. You can specify either the device or the mount point.
  8. For persistent mounts, edit /etc/fstab to adjust the mount settings.

Networking in a VM

NAT mode: Shares an IP address with the host through NAT and creates a virtual gateway service. Both the host and the VM connect to this gateway. The virtual gateway acts as a proxy service, allowing all devices on the NAT subnet to access the real host’s network.

Bridged mode: Creates a virtual hub or switch that connects the VM directly to the real host’s network link. The VM is visible on the local network and uses an IP address from the real local network.

Host-only mode: The host and VM connect to each other through network adapters, but cannot access the internet.

To change the VM’s IP address, edit the configuration in vim /etc/sysconfig/network-scripts/ifcfg-network_adapter_name.

TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=static  //静态ip
IPADDR="192.168.6.100"  //ip地址
NETMASK="255.255.255.0"  //子网掩码
GATEWAY="192.168.6.1"  //网关
DNS1="192.168.6.1"   //dns
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=default
NAME=ens160
UUID=4ded5bf3-4709-4de5-a0eb-4eb41f04cd81
DEVICE=ens160
ONBOOT=yes  //开机时启用

Process-Related

  1. top displays or manages running programs
    1. -i displays only active processes
    2. -d specifies the number of seconds between refreshes
    3. -p specifies the ID of the process to monitor
  2. ps process status: -a displays processes on all terminals; -u displays processes by user; -x displays runtime parameters for background processes
    1. ​ ps -aux
    2. ​ ps -ef displays all current processes in full format
  3. kill 8888 terminates the process with PID 8888
    1. -9 forcefully terminates the process
    2. Can force another user to log out; can temporarily disable remote login via sshd
  4. killall terminates processes and their child processes
  5. pstree -up displays currently running processes in a tree structure
  6. ntsysv graphically manages services
  7. netstat checks the system's network status
    1. -an displays detailed information
    2. -l displays ports only

Firewall

  1. netstat -anp checks network status on a Linux system and can be used to troubleshoot port conflicts
  2. firewall-cmd -permanent --add-port=port/protocol
  3. firewall-cmd -permanent --remove-port=port/protocol
  4. firewall-cmd --reload reloads the firewall rules
  5. firewall-cmd -query-port=port/protocol

RPM Package Management Tool

  1. rpm -qa lists all packages

  2. rpm -q name queries the package named name

  3. rpm -qi queries package information

  4. rpm -ql lists the files in a package

  5. rpm -qf file_path queries which package a file belongs to

  6. rpm -ivh (rpm_file) installs the specified RPM file

    1. i — install
    2. v — verbose; displays messages
    3. h — hash; displays a progress bar

Environment Variables

On Linux, environment variables are configured by modifying the /etc/profile file.

export JAVA_HOME=/......./
PATH=$JAVA_HOME/bin
  • export is a true environment variable. Without export, it is a Bash variable, but adding a Bash variable to PATH has the same effect
  • After making changes, run source /etc/profile to apply them
  • Use echo $PATH to check whether it is configured correctly
  • Do not put spaces around =, or an error will occur

Shell programming

  1. Specify the interpreter on the first line of the file #!/bin/bash
  2. '' denotes a string
  3. # single-line comment
  4. :<<! ! multiline comment, on a line by itself
  5. $ reference a variable
  6. unset destroy a variable
  7. readonly read-only variable; cannot be destroyed
  8. `` backticks denote a command
  9. Positional parameters Pass arguments when executing
    1. $n Get the nth positional parameter. If n is greater than 10, use ${10}
    2. $* All arguments, treated as a single unit
    3. $@ All arguments, treated individually; output is similar to $*
    4. $# Number of arguments
  10. Predefined variables
    1. $$ PID of the current script
    2. $! PID of the last process
    3. $? Exit status of the previous command; 0 means success
  11. Shell expressions
    1. `expr 1+1 `
    2. $(1+1)
    3. $[1+1]
  12. Conditional tests
    1. Strings

      1. = Whether they are equal
    2. Integers

      1. -lt Less than
      2. -le Less than or equal to
      3. -eq Equal to
      4. -gt Greater than
      5. -ge Greater than or equal to
      6. -ne Not equal to
    3. Permissions

      1. -r Read
      2. -w Write
      3. -x Execute
    4. File types

      1. -f File exists
      2. -e File or directory exists
      3. -d Directory exists
  13. Conditional statements
    1. if [ expression ] then execute statements fi Returns true if non-empty
    2. Example: [expression] && echo ok ||echo "not ok"

echo

The print command. Usage:

echo 			# 输出一个空行
echo hello 		# 输出hello并换行
echo -n hello 	# 输出hello

# 调用变量
name=zhangsan
echo $name
# 打印上一个程序的退出状态码 
echo $? 		# 0是成功执行正常退出,非0就是有意外情况

# 查看上一条命令的执行详情
echo !!

# 查找某条命令的执行详情
echo !l			# 最近一条以l开头的命令

How to print special characters such as $

echo \$name
echo '$name'

Special case may be triggered on legacy Red Hat-family distributions

echo "hello world!"
# 报错,搜寻以”开头的命令找不到

-e option enables escaping.

echo -e "hello\nworld"

bash

A Linux command interpreter that executes user commands in a text window.

It works similarly to the Python interpreter.

Command-line expansion

Use {}. Example:

echo {1..100}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
echo {1..100}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
echo {a..z}
a b c d e f g h i j k l m n o p q r s t u v w x y z

Command Alias

alias 					# 展示全部别名
alias grep='grep --color=auto'
alias l='ls -CF'
alias la='ls -A'
alias ll='ls -l'
alias ls='ls --color=auto'

alias rm='rm -i'		# 新增命令别名
unalias rm				# 删除命令别名

Command History

history 		# 展示命令历史
!行号			#重复执行命令中的某一行
!! 			#重复执行上次命令

Bash Keyboard Shortcuts

ctrl + a 	# 光标到行首
ctrl + e 	# 光标到行首
ctrl + k 	# 删除后面的命令
ctrl + u 	# 删除前面的命令
ctrl + l 	# 清屏

Command Completion & File Path Completion

Press Tab to complete commands found in PATH, or file and directory paths.

RegExp Regular Expressions

Regular Expression: Regular Expressions

Use symbols to quickly filter, replace, and process the desired strings.

Characteristics:

  • Regular expressions are a set of rules and methods.
  • Regular expressions work line by line, processing one line at a time.
  • In Linux, they are generally supported only by sed, grep, and awk.

The Linux Three Musketeers Three important Linux tools

  • sed — text editor
  • awk — text formatter
  • grep — text filter

Categories of Regular Expressions (as classified among the Three Musketeers)

  • Basic Regular Expressions (BRE)

    如 ^$.[]*
    
  • Extended Regular Expression (ERE)

    在BRE基础上新增了 (){}?+|等
    

Functions of Basic Regular Expressions:

  1. Match characters
  2. Match repetitions
  3. Anchor positions

image-20240804105153982

Basic Regular Expressions:

Extended expressions require grep -E (to enable extended mode).

Character Function
+ Match a character one or more times
[:/]+ Match : or / one or more times
? Match a character zero or one time
| Means “or”
( ) Grouping filter; the enclosed content is one unit
a{1,2} Match a character 1–2 times
a{1,} One or more times
a{1} Once
a{,2} 0–2 times

sed (stream editor)

A stream editor; “stream” means that processing is performed one line at a time.

Usage:

sed -e (expression) file. Multiple -e parameters can be specified to execute multiple expressions.

You can also write expressions to a file, then use the -f parameter to read and execute the script in that file.

By default, it only prints the output. Use the -i parameter to write the changes to the file.

Use -ie to write the changes and back up the original file.

For text, the four common operations are:

  • Add
  • Delete
  • Modify
  • Query

Assume the contents of the file test are as follows.

1
2
3
4
5

Writing Expressions

[Line condition] Operation \ Content

If no line condition is specified, the operation applies to all lines.

Append Operation

a, append: add a new line after the specified line

sed -e '1a\new line' test
1
new line
2
3
4
5

i, insert: Insert a new line before the specified line.

sed -e '1i\new line' test
new line
1
2
3
4
5

Delete Operation

d, delete deletes the specified line

sed -e '1d' test'
2
3
4
5

Change Commands

c, change a line

sed -e '1c\test change line' test 
test change line
1
2
3
4
5

s, replace one or more strings in the corresponding lines with the target string (most commonly used, and supports regular expressions)

Test content:

top line
a new line
new new line

Modify locally (replace at most one per line):

sed 's/new/old/' test
top line
a old line
old new line

Modify multiple (replace with however many there are):

sed 's/new/old/g' test
top line
a old line
old old line

Query Operations (Print)

p Output the corresponding line

sed '1p' test
top line
top line
a new line
new new line

During output, the output from p conflicts with the contents of sed’s default output buffer, causing duplicate output.

Use the -n option to disable buffer output and print only the lines we specify.

sed -n '1p' test
top line

Summary

image-20240803211919007

Additional sed Notes (Using Regular Expressions)

The address portion of a sed expression can use regular expressions to match lines, and process the lines that match successfully.

sed -r enables extended regular expressions.

image-20240804140157400

image-20240804140039965

image-20240804140100991

grep

The Linux grep (global regular expression) command is used to search files or piped data streams for strings or regular expressions that meet specified criteria.

Syntax

grep [options] pattern [files]
或
grep [-abcEFGhHilLnqrsvVwxy][-A<显示行数>][-B<显示列数>][-C<显示列数>][-d<进行动作>][-e<范本样式>][-f<范本文件>][--help][范本样式][文件或目录...]
  • pattern - The string or regular expression to search for.
  • files - The names of the files to search. Multiple files can be searched at the same time. If the files parameter is omitted, data is read from standard input by default.

Common options::

  • -E: Enable extended regular expressions extend

  • -o: Show only the matching strings themselves only

  • -i: Match while ignoring case ignore

  • -v: Search in reverse; print only lines that do not match

  • -n: Show the line numbers of matching lines number

  • -c: Print the number of matching lines

Grouping syntax ()

Bundle multiple characters together and process them as a single unit.

(was|ad) (grouping) matches either was or wad

(was).*\1 (reuse) \1 references the first group again

awk

awk was originally named gawk. It is usually used for processing text formats, but it is actually a programming language too (Crazzy!).

Basics

awk syntax:

awk	options	parttern {action} file
    参数		模式		动作

Field references:

  • $0: Represents the entire line of text.
  • $1: Represents the first field.
  • $2: Represents the second field, and so on.
  • $NF: Represents the last column.

In awk, fields are separated by the field separator. By default, awk uses spaces or tabs as field separators, but you can specify a different separator by setting the FS variable.

awk '{ print $1, $2, $3 }' data.txt
# 打印每一行的第一列 第二列 第三列。
awk 'BEGIN {FS = ","} {print $2}' test
# 指定以逗号分隔字段。

exmaple

# ens33 的ipv4地址
ip addr show ens33 | awk 'NR==4 {print $2}' | awk 'BEGIN {FS="/"} {print $1}'
192.168.6.66

# ens33 的ipv4地址 (正则方式)
ip addr show ens33 | awk '/inet / {print $2}' | awk 'BEGIN {FS="/"} {print $1}'
192.168.6.66

# 所有的ipv4地址
ip addr | awk '/inet / {print $2}' | awk 'BEGIN {FS="/"} {print $1}'
127.0.0.1
192.168.6.66
172.17.0.1

# 所有的ip地址
ip addr | awk '/inet/ {print $1": "$2}' | awk 'BEGIN {FS="/"} {print $1}'
inet: 127.0.0.1
inet6: ::1
inet: 192.168.6.66
inet6: fe80::20c:29ff:fed8:bcf0
inet: 172.17.0.1