-i #: Create an inode for every number of bytes in the data space; this size should not be less than the block size;
-N #: How many inodes are created for the data space;
-m #: The percentage of space reserved for managers;
-O FEATURE[,...]: Enable the specified feature
-O ^FEATURE: Turn off the specified feature
mkswap: Create swap partition
mkswap [options] device
-L 'LABEL'
Prerequisite: Adjust the ID of the partition to 82;
Others Commonly used tools:
blkid: View block device attribute information
blkid [OPTION]... [DEVICE]
-U UUID: Find the corresponding device based on the specified UUID
-L LABEL: Find the corresponding device based on the specified LABEL
e2label: LABEL for managing ext series file systems
# e2label DEVICE [LABEL]
tune2fs: Reset the value of the adjustable parameters of the ext series file system
-l: View the super block information of the specified file system; super block
-L 'LABEL': Modify the volume label
-m #: Modify the percentage of space reserved for administrators
-j: Upgrade ext2 to ext3
-O: Enable or disable file system properties
-o: Adjust the default mount options of the file system
-U UUID: Modify the UUID number;
dumpe2fs:
-h: View super block information
File system detection:
fsck: File System CheCk
fsck.FS_TYPE
fsck -t FS_TYPE
-a: Automatically fix errors
-r: Interactively fix errors
Note: FS_TYPE must be the same type as the existing files on the partition;
e2fsck: A dedicated detection and repair tool for ext series files
-y: The automatic answer is yes;
-f: Forced repair;
File system management:
The act of establishing an association between an additional file system and an existing directory in the root file system, so that this directory serves as an access entry for other files, is called mounting;
The process of releasing this association is called uninstallation;
Associate the device with the mount point: Mount Point
mount
When uninstalling: You can use the device or the mount point
umount
Note: The original files under the mount point will be temporarily hidden after the mount is completed;
Mounting method: mount DEVICE MOUNT_POINT
mount: Display all devices mounted on the current system by viewing the /etc/mtab file
mount [-fnrsvw] [-t vfstype] [-o options] device dir
device: Specify the device to be mounted;
(1) Device file: for example/dev/sda5
(2) Volume label: -L 'LABEL', for example -L 'MYDATA'
(3) UUID, -U 'UUID': For example -U '0c50523c-43f1-45e7-85c0-a126711d406e'
( 4) Pseudo file system name: proc, sysfs, devtmpfs, configfs
dir: The mount point
already exists; it is recommended to use an empty directory ;
The device being used by the process cannot be uninstalled;
Common command options:
-t vsftype: Specify the file system type on the device to be mounted;
-r: readonly, read-only mount;
-w: read and write, read-write mount;
-n: do not update /etc/mtab;
-a: Automatically mount all devices that support automatic mounting; (defined in the /etc/fstab file, and there is an "auto-mount" function in the mounting options)
-L 'LABEL': Specify the device to be mounted with the volume label;
-U 'UUID': Specify the device to be mounted with the UUID;
-B, --bind: Bind the directory to another directory;
Note: Check the mounted files tracked by the kernel All devices: cat /proc/mounts
-o options: (Options for mounting the file system)
async: asynchronous mode;
sync: synchronous mode;
atime/noatime: including directories and files;
diratime/nodiratime: Access timestamp of the directory
auto/noauto: Whether to support automatic mounting
exec/ noexec: Whether to support running applications on the file system as a process
dev/nodev: Whether to support the use of device files on this file system;
suid/nosuid:
remount: Remount
ro:
rw :
user/nouser: Whether ordinary users are allowed to mount this device
acl: Enable the acl function on this file system
Note: The above options can be used multiple times at the same time, separated by commas;
Default mount options: defaults
rw, suid, dev, exec, auto, nouser, and async
Uninstall command:
# umount DEVICE
# umount MOUNT_POINT
View the processes that are accessing the specified file system:
fuser -v MOUNT_POINT
Terminate all processes that are accessing the specified file system:
# fuser -km MOUNT_POINT
Mount swap partition:
Enable: swapon
##swapon [OPTION]... [DEVICE]
-a: Activate all swap partitions;
-p PRIORITY: Specify priority;
Disable: swapoff [OPTION]... [DEVICE]
Memory space usage status:
free [OPTION]
-m: in MB
-g: in GB
Tool for viewing information such as file system space usage:
df:
-h: human- readable
-i:inodes instead of blocks
-P: Output in Posix-compatible format;
View the overall space usage status of a directory:
du:
du [OPTION].. . DIR
-h: human-readable
-s: summary
Commands described: mount, umount, free, df, du, swapon, swapoff, fuser
Configuration file for file mounting: /etc/fstab
Each line defines a file system to be mounted;
The device or pseudo device to be mounted File systemMount pointFile system type Mount optionsDump frequency Self-test sequence
The device or pseudo file system to be mounted:
Device file, LABEL(LABEL=""), UUID( UUID=""), pseudo file system name (proc, sysfs)
Mount options:
defaults
Dump frequency:
0: No backup
1: Daily dump
2: Every other day dump
Self-test sequence:
0: No self-check
1: Self-check first; generally only rootfs uses 1;
...
Other concepts on the file system:
Inode: Index Node, index node
Address pointer:
Direct pointer:
Indirect pointer:
Third-level pointer:
inode bitmap: status information that identifies whether each inode is idle;
Linked file:
Hard link:
Cannot be linked directory;
cannot be performed across partitions;
points to multiple different paths to the same inode; creating a hard link to the file is The inode creates a new reference path, thus increasing its reference count;
Symbolic link:
can be performed on the directory;
can be performed across partitions;
points to the path of another file; its size is the length of the path string pointed to; does not increase or decrease the reference count of the target file inode;
ln [-sv] SRC DEST
-s: symbolic link
-v: verbose
The impact of file management operations on files:
File deletion:
File Copy:
File move:
1. Create a 20G file system with a block size of 2048 and a file The system is ext4, and the volume label is TEST. This partition is required to be automatically mounted to the /testing directory after booting, and has the acl mounting option by default;
(1) Create a 20G partition;
(2) Format:
mke2fs -t ext4 -b 2048 -L 'TEST' /dev/DEVICE
(3) Edit the /etc/fstab file
LABEL='TEST' /testing ext4 defaults,acl 0 0
3. Write a script to complete the following functions:
(1) List all disk devices recognized by the current system;
(2) If the number of disks is 1, display its space usage information;
Otherwise, the space usage information on the last disk is displayed;
Multiple physical volume support: btrfs can be composed of multiple underlying physical volumes; supports RAID, with online "add", "remove", and "modify";
Copy-on-write update mechanism (CoW): copy, update and replace pointers instead of "in-place" updates;
zcat: View the text file content without explicit expansion;
2、bzip2/bunzip2/bzcat
##bzip2 [OPTION]... FILE ...
-k: keep, keep the original file;
-d: decompress
-#: 1-9, compression ratio, default is 6;
bzcat: Without explicit expansion View the content of the text file;
##3、xz/unxz/xzcat
##bzip2 [ OPTION]... FILE ...
-k: keep, keep the original file;
-d: decompress
-#: 1-9, compression ratio, default is 6;
xzcat: Without explicit expansion View the content of the text file;
4、tar
tar [OPTION].. .
(1) Create archive
tar -c -f /PATH/TO/SOMEFILE.tar FILE ...
##tar -cf /PATH/TO/SOMEFILE.tar FILE...
(2) View the file list in the archive
tar -t -f /PATH/TO/SOMEFILE.tar
(3) Expand the archive
tar -x -f /PATH/TO/SOMEFILE.tar
tar -x -f /PATH/TO/SOMEFILE.tar -C /PATH/TO/DIR
Combined with compression tools to achieve: archiving And compress
##-j: bzip2, -z: gzip, -J: xz
bash scripting:
##if statement, bash -n, bash -x
CONDITION:
bash command:
Use the execution status result of the command;
Success : true
Failure: flase
The meaning of success or failure: depends on the command used;
Single branch:
if CONDITION; then
if-true
fi
Double branch:
if CONDITION; then
if-true
else
if-false
fi
Multiple branches:
if CONDITION1; then
if-true
elif CONDITION2; then
if-ture
elif CONDITION3; then
if-ture
...
esle
all-false
fi
Make judgments condition by condition, No. When a "true" condition is encountered, its branch is executed and then ends;
Example: The user enters the file path and the script determines the file type;
#!/bin/bash
read -p "Enter a file path: " filename
if [ -z "$filename" ]; then
## echo "Usage: Enter a file path."
exit 2
fi
if [ ! -e $filename ]; then
echo "No such file."
## exit 3
fi
if [ -f $filename ]; then
echo "A common file."
elif [ -d $filename ]; then
echo "A directory."
elif [ -L $filename ]; then
echo "A symbolic file."
else
echo "Other type."
fi
## Note: if statements can be nested;
Loop: for, while, until
Loop body: to be executed Code; may be executed n times;
Entry condition:
Exit condition:
for loop:
##for variable name in list; do
Loop body
done
Execution mechanism:
Assign the elements in the list to the "variable name" in sequence "; The loop body is executed once after each assignment; until the elements in the list are exhausted, the loop ends;
Example: Add 10 users, user1- user10; password is the same as username;
##Example: Determine the types of all files under a certain path
#!/bin/bash
#for file in $(ls /var); do
if [ -f /var/$file ]; then
echo "Common file."
elif [ -L /var/$file ]; then
echo "Symbolic file."
elif [ -d /var/$file ]; then
##echo "Directory."
else
echo "Other type."
fi
done
##Example:
#!/bin/bash
declare -i estab=0
declare -i listen=0
declare -i other=0
for state in $( netstat -tan | grep "^tcp\>" | awk '{print $NF}'); do
if [ "$state" == ' ESTABLISHED' ]; then
let estab++
elif [ "$state" == 'LISTEN' ]; then
let listen++
## else
##let other++
fi
done
echo "ESTABLISHED: $estab"
echo "LISTEN: $listen"
echo "Unkown: $other"
/ There are multiple files starting with K and S in the etc/rc.d/rc3.d directory;
Read each file separately, and output the file starting with K Add stop to the file. The output of the file starting with S is the file name plus start;
"K34filename stop"
"S66filename start"
##Linux Package Management:
API:Application Programming Interface
POSIX:Portable OS
Program source code --> Preprocessing --> Compile --> Assembly --> Link
Static compilation:
Shared compilation: .so
ABI: Application Binary Interface
Incompatible between Windows and Linux
Library Level of virtualization:
Linux: WINE
Windows: Cywin
System-level development
C
C++
Application-level development
java
Python
php
perl
ruby
Components of a binary application:
Binary files , library files, configuration files, help files
Package manager:
debian: deb, dpt
redhat: rpm, rpm
rpm: Redhat Package Manager
RPM is Package Manager
Gentoo
##Archlinux
##Source code: name-VERSION.tar.gz
VERSION: major.minor.release
rpm package naming method:
name-VERSION-release.arch.rpm
VERSION: major.minor.release
release.arch:
release:release.OS
zlib- 1.2.7-13.el7.i686.rpm
Common arch:
x86: i386, i486 , i586, i686
##x86_64: x64, x86_64, amd64
powerpc: ppc
Platform independent: noarch
testapp: Unpacking
testapp-VERSION-ARCH.rpm: Main package
testapp-devel -VERSION-ARCH.rpm: Branch package
testapp-testing-VERSION-ARHC.rpm
package Between: There are dependencies
X, Y, Z
##yum: the front-end tool of the rpm package manager;
View the library files that binary programs depend on:
ldd /PATH/TO/BINARY_FILE
Manage and view library files loaded on this machine:
ldconfig
/sbin/ldconfig -p: Displays all available library file names and file path mappings that have been cached on this machine;
The configuration files are: /etc/ld.so.conf, /etc/ld.so.conf.d/*.conf
## Cache file: /etc/ld.so.cache
Package management:
Function: Compile Each component file of the application program is packaged into one or several package files, so as to conveniently and quickly implement management operations such as installation, uninstallation, query, upgrade and verification of the program package;
1. List of program components (unique to each package)
File list
When installing or uninstalling Running script
2, database (public)
Package name and version
Dependencies;
Function description;
The file path and verification code information of each file generated by the installation;
upgrage: "Upgrade" if an older version of the package is installed; if it does not exist If the old version package is installed, then "install";
freeshen: If the old version package is installed, then "upgrade"; if the old version package does not exist, the upgrade operation will not be performed;
rpm -Uvh PACKAGE_FILE ...
rpm -Fvh PACKAGE_FILE ...
--oldpackage: downgrade;
--force: forced upgrade;
Note: (1) Do not upgrade the kernel; Linux supports the coexistence of multiple kernel versions, therefore, install the new version of the kernel directly;
(2) If the original package The configuration file has been modified after installation. When the level is long, the same configuration file provided by the new version will not directly overwrite the old version of the configuration file, but the new version of the file will be renamed (FILENAME.rpmnew) and retained;
Query:
rpm {-q|--query} [select-options] [query-options]
[select-options]
-a: All packages
-f: View which package the specified file was generated by
-p /PATH/TO/PACKAGE_FILE: Query for package files that have not yet been installed Operation;
--whatprovides CAPABILITY: Query which package the specified CAPABILITY is provided by;
--whatrequires CAPABILITY: Query which package the specified CAPABILITY depends on;
[query-options]
--changelog : Query the changelog of the rpm package
-c: Query the configuration file of the program
-d: Query the documentation of the program
-i: information
-l: View all files generated after the specified package is installed;
--scripts: script fragments that come with the package
-R: Query the CAPABILITY that the specified package depends on;
-- provides: Lists the CAPABILITY provided by the specified package;
Multiple files: There may be cross-file dependencies between the codes in the file;
C, C++: make (configure --> Makefile.in --> makefile)
java: maven
##C code compilation and installation three steps:
./configure:
(1) Pass parameters through options, specify enabled features, installation Path, etc.; when executing, the makefile will be generated with reference to the user's specification and the Makefile.in file;
(2) Check the external environment it depends on;
make:
Build the application based on the makefile;
make install
Development tools:
autoconf: Generate configure script
automake: Generate Makefile.in
Recommendation: Check INSTALL and README before installation
Obtain the source code of the open source program:
Official self-built site:
apache.org (ASF)
mariadb.org
...
Code hosting:
SourceForge
Github.com
code.google.com
c/c++: gcc (GNU C Complier)
Compile C source code:
Premise: Provide development tools and development environment
Development tools: make, gcc, etc.
Development environment: development library , header file
glibc: Standard library
Provide development components through "package group"
DEVICE: The device to which this configuration file applies;
HWADDR: The MAC address of the corresponding device;
BOOTPROTO: The address configuration protocol used when activating this device, commonly used dhcp, static, none, bootp;
NM_CONTROLLED: NM is the abbreviation of NetworkManager; whether this network card accepts NM control; CentOS6 recommends "no";
ONBOOT: whether to activate this device when the system boots;
TYPE: interface type; common Ethernet, Bridge;
UUID: unique identifier of the device;
IPADDR: Specify the IP address;
NETMASK: subnet mask;
GATEWAY: default gateway;
DNS1: the first one DNS server pointing;
DNS2: The second DNS server pointing;
USERCTL: Whether ordinary users can control it This device;
PEERDNS: If the value of BOOTPROTO is "dhcp", whether to allow the dns server pointing information assigned by the dhcp server to be directly overwritten into the /etc/resolv.conf file;
/etc/sysconfig/network-scripts/route-IFACE
Two styles:
(1) TARGET via GW
(2) Define a route every three lines
ADDRESS#=TARGET
##NETMASK#=mask
##GATEWAY#=GW
Configure multiple addresses for the network card:
ifconfig:
##ifconfig IFACE_ALIAS
ip
ip addr add
Configuration file:
##ifcfg-IFACE_ALIAS
DEVICE=IFACE_ALIAS
Note: Gateway alias cannot be booted using dhcp protocol;
Linux network attribute configuration tui (text user interface):
system-config-network-tui
You can also use setup to find it;
Note: Remember to restart the network service to take effect;
Configure the host name of the current host:
hostname [HOSTNAME]
/etc/sysconfig/network
HOSTNAME=
The network interface identifies and names the associated udev configuration file:
/etc/udev/rules.d/70-persistent-net.rules
##Uninstall the network card driver:
modprobe -r e1000
Load the network card driver:
modprobe e1000
##CentOS 7 network property configuration
Traditional naming : Ethernet eth[0,1,2,...], wlan[0,1,2,...]
Predictable function
udev supports several different naming schemes:
Firmware, Topology
(1) Network card naming mechanism
systemd naming method for network devices:
(a ) If the index information provided by Firmware or BIOS for the device integrated on the motherboard is available and predictable, the name is based on this index, such as eno1;
(b) If Firmware or BIOS is The index information provided by the PCI-E expansion slot is available and predictable, so it is named according to this index, such as ens1;
(c) If the physical location information of the hardware interface is available, Then name it based on this information, such as enp2s0;
(d) If the user explicitly starts it, you can also name it based on the MAC address, enx2387a1dc56;
(e) When none of the above are available, the traditional naming mechanism will be used;
Some of the above naming mechanisms require the participation of the biosdevname program;
(2) Name composition format
en: ethernet
##wl : wlan
##ww: wwan
## Name type:
o: The device index number of the integrated device;
c Sort processes by CPU% b Bytes or bits for network I/O
m Sort processes by MEM% w Delete warning logs
p Sort processes by name x Delete warning and critical logs
i Sort processes by I/O rate 1 Global CPU or per-CPU stats
d Show/hide disk I/O stats h Show/hide this help screen
f Show/hide file system stats t View network I/O as combination
n Show/hide network stats u View cumulative network I/O
s Show/hide sensors stats q Quit (Esc and Ctrl-C also work)
y Show/hide hddtemp stats
常用选项:
-b: 以Byte为单位显示网卡数据速率;
-d: 关闭磁盘I/O模块;
-f /path/to/somefile: 设定输入文件位置;
-o {HTML|CSV}:输出格式;
-m: 禁用mount模块
-n: 禁用网络模块
-t #: 延迟时间间隔
-1:每个CPU的相关数据单独显示;
C/S模式下运行glances命令:
服务模式:
glances -s -B IPADDR
IPADDR: 指明监听于本机哪个地址
客户端模式:
glances -c IPADDR
IPADDR:要连入的服务器端地址
dstat命令:
dstat [-afv] [options..] [delay [count]]
-c: 显示cpu相关信息;
-C #,#,...,total
-d: 显示disk相关信息;
-D total,sda,sdb,...
-g:显示page相关统计数据;
-m: 显示memory相关统计数据;
-n: 显示network相关统计数据;
-p: 显示process相关统计数据;
-r: 显示io请求相关的统计数据;
-s: 显示swapped相关的统计数据;
--tcp
--udp
--unix
--raw
--socket
--ipc
--top-cpu:显示最占用CPU的进程;
--top-io: 显示最占用io的进程;
--top-mem: 显示最占用内存的进程;
--top-lantency: 显示延迟最大的进程;
kill命令:
Send control signals to the process to achieve process management
Display available signals in the current system:
# kill -l
man 7 signal
##Commonly used signals:
1) SIGHUP: Let it reread the configuration file without closing the process;
2) SIGINT: Abort the running process; equivalent to Ctrl+c ;
9) SIGKILL: Kill the running process;
15) SIGTERM: Terminate the running process;
18) SIGCONT:
19) SIGSTOP:
##Method to specify the signal :
(1) Numeric identification of the signal; 1, 2, 9
(2) Complete name of the signal; SIGHUP
(3) The abbreviated name of the signal; HUP
##Send a signal to the process:
kill [-SIGNAL] PID...
Kill all processes under "name":
killall [-SIGNAL] Program
##Linux job control
##Foreground job: Started through the terminal, and will always occupy the terminal after startup;
Background job: can be started through the terminal, but it will run in the background after startup (release the terminal);
How to make the job run in the background?
(1) Running job
Ctrl+z
(2) Not yet Started job
# COMMAND &
##Although this type of job is sent to the background to run, it is still related to Terminal related; if you want to send it to the background, peel off the relationship with the terminal:
# nohup COMMAND &
View all jobs:
# jobs
##Job Control:
# fg [[%]JOB_NUM]: Bring the specified background job back to the foreground;
# bg [[%]JOB_NUM]: Let the job sent to the background continue to run in the background ;
# kill [%JOB_NUM]: Terminate the specified job;
Process priority adjustment:
Static priority: 100-139
The nice value when the process is started by default is 0 and the priority is 120;
nice command:
nice [OPTION] [COMMAND [ARG]...]
renice command:
renice [-n] priority pid...
View:
ps axo pid,comm,ni
Not covered Command: sar, tsar, iostat, iftop
##Linux task planning, periodic task execution
Execute a task at a certain time in the future: at, batch
Run a task periodically: cron
Email service:
smtp: simple mail transmission protocol, used to transmit emails;
pop3: Post Office Protocol
imap4: Internet Mail Access Protocol
##mailx - send and receive Internet mail
MUA:Mail User Agent
##mailx [-s 'SUBJECT'] username[@hostname]
Generation of email body:
(1) Give it directly, Ctrl+d;
(2) Input redirection;
(3) Through pipe;
echo -e " How are you?\nHow old are you?" | mail
mailx
at command:
at [option] TIME
TIME:
HH:MM [YYYY-mm-dd]
noon, midnight, teatime
tomorrow
now+#{minutes, hours, days, OR weeks}
##Common options:
-q QUEUE:
-l: Lists jobs waiting to be run in the specified queue; equivalent to atq
- d: Delete the specified job; equivalent to atrm
-c: View specific job tasks;
-f /path/from/somefile : Read the task from the specified file;
Note: The execution result of the job will be notified to the relevant users by email;
batch command:
Let the system choose its own free time to perform the tasks specified here;
Periodic task schedule: cron
Related packages:
cronie: main package, provides crond Daemon processes and related auxiliary tools;
cronie-anacron: a supplementary program for cronie; used to monitor the execution status of cronie tasks; if the tasks in cronie failed to run at the time point in the past If it runs normally, anacron will subsequently start this task;
crontabs: contains system maintenance tasks provided by CentOS;
Make sure the crond daemon is running:
CentOS 7:
##systemctl status crond
...running...
CentOS 6:
service crond status
Tasks scheduled to be executed periodically are submitted to crond, which implements point-to-point execution.
# | | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
| | | | | |
* * * * * user-name command to be executed
For example: Run the echo command at 9:10 pm;
10 21 * * * gentoo /bin/echo "Howdy!"
Time representation:
(1) Specific value;
Values within the valid value range at a given time point;
(2) *
All values within the valid value range at a given time point;
means "every...";
(3 ) Discrete values:,
#,#,
#(4) Continuous values:-
#-#
(5) In the specified time range, define the step size:
/#: # is the step size
For example: echo command every 3 hours;
0 */3 * * * gentoo /bin/echo "howdy!"
User cron:
crontab command definition, each user has a dedicated cron task file: /var/spool/cron /USERNAME
crontab command:
##crontab [-u user] [-l | -r | -e ] [-i]
-l: List all tasks;
-e: Edit tasks;
-r: Remove all tasks;
-i: Used with -r to allow users to selectively remove specified tasks in interactive mode;
-u user: Only root can run, and manages cron tasks for the specified user;
# #Note: The running results will be notified to relevant users by email;
(1) COMMAND > /dev/null
(2) COMMAND &> /dev/null
##For cron tasks, % has a special purpose; if you want to use % in a command, you need to escape it; however, If you place % in single quotes, you don’t need to escape it;
Thinking:
(1) How to run a task in seconds?
* * * * * for min in 0 1 2; do echo "hi"; sleep 20; done
(2) How To run a task every 7 minutes?
sleep command:
sleep NUMBER[SUFFIX]...
SUFFIX:
s: seconds, default
m: Minutes
h: hour
d: day
;
Startup process of CentOS 5 and 6
Linux: kernel+rootfs
Library: function collection, function, calling interface
Process call: procedure
Function call: function
##Program
Kernel design school:
Single-kernel design: Linux
Integrate all functions into the same program;
Microkernel design: Windows, Solaris
Each function is implemented using a separate subsystem;
Linux kernel features:
Support modularization: .ko
Supports dynamic loading and unloading of modules ;
Components:
Core file:/boot/vmlinuz-VERSION-release
ramdisk:
CentOS 5: /boot/initrd-VERSION-release.img
CentOS 6: / boot/initramfs-VERSION-release.img
Module file:/lib/modules/VERSION-release
CentOS system startup process:
POST: power-on self-test;
ROM: CMOS
BIOS:Basic Input and Output System
##ROM+RAM
BOOT Sequence:
Search each boot device in order. The first device with a boot program is the device used for this startup;
bootloader: boot loader, program
windows: ntloader
Linux:
LILO :LInux LOader
GRUB: GRand Uniform Bootloader
GRUB 0.X: GRUB Legacy
GRUB 1.x: GRUB2
#Function: Provide a menu that allows the user to choose to start the system or a different kernel version; load the user-selected kernel Go to a specific space in the memory, decompress, expand, and transfer system control to the kernel;
MBR:
446: bootloader
64: fat
2: 55AA
GRUB:
bootloader: 1st stage
disk: 2nd stage
kernel:
Self-initialization:
Detect all identifiable hardware devices;
Load the hardware driver; (you may use ramdisk to load the driver)
Mount the root file system in read-only mode;
Run the first application in user space: /sbin/init
Run level: Set for application purposes such as system operation or maintenance;
0-6: 7 levels
0: Shutdown
1: Single user mode (root, no login required), single, maintenance mode;
2: Multi-user mode, the network function will be started, but NFS will not be started; maintenance mode;
3: Multi-user mode, normal mode; Text interface;
4: Reserved level; can be the same as level 3;
5: Multi-user mode, normal mode; graphical interface;
6: Restart
Default level:
3, 5
Switch level:
init
#View level:
runlevel
who -r
Configuration file:/etc/inittab
Each line defines an action and its corresponding process
id:runlevel:action:process
action:
wait: Switch to this level and run once;
respawn: If this process terminates, restart it;
initdefault: Set the default run level; process is omitted;
sysinit: Set the system initialization method. Generally, /etc/rc.d/rc.sysinit is specified here;
...
id:3:initdefault:
si::sysinit:/etc/rc.d/rc.sysinit
l0:0:wait:/etc/rc.d/rc 0
##l1:1:wait:/ etc/rc.d/rc 1
...
l6:6:wait:/etc/rc.d/rc 6
Explanation: rc 0 --> means reading /etc/rc.d/rc0.d/
K*: K##*: ##Running order; the smaller the number, the earlier it runs; the smaller the number, the service usually depends on other services;
S*: S##*: ##Running order; the smaller the number, the earlier it runs; the service with the smaller number is usually the service that is relied on;
for srv in /etc/rc.d/rc0.d/K*; do
$srv stop
done
for srv in /etc/rc.d/rc0.d/S*; do
$srv start
done
chkconfig command
View services at all levels Startup or shutdown settings:
chkconfig [--list] [name]
Add:
The SysV service script is placed in /etc/rc.d/init.d (/etc/init.d)
chkconfig --add name
#!/bin/bash
## chkconfig: LLLL nn nn
Delete:
chkconfig --del name
Modify the specified link type
chkconfig [--level levels] name
--level LLLL: Specify the level to be set; when omitted, it means 2345;
Note: Normal level, the last service S99local started is not linked to a service script in /etc/rc.d/init.d, but points to the /etc/rc.d/rc.local script; therefore, it is inconvenient or unnecessary to write it as a service The script is placed in the /etc/rc.d/init.d/ directory, and the command that you want to run automatically when the computer is turned on can be placed directly in the /etc/rc.d/rc.local file;
tty1:2345:respawn:/usr/sbin/mingetty tty1
tty2:2345:respawn:/usr/sbin/mingetty tty2
...
##tty6:2345:respawn:/usr/sbin/mingetty tty6
minggetty will call the login program
/etc/rc.d/rc.sysinit: system initialization script
(1) Set the host name;
(2) Set the welcome message;
(3) Activate udev and selinux;
(4) Mount the file system defined in the /etc/fstab file;
(5) Detect the root file system, And remount the root file system in read-write mode;
(6) Set the system clock;
(7) Activate the swap device;
(8) Set kernel parameters according to the /etc/sysctl.conf file;
(9) Activate lvm and software raid devices;
(10) Load additional device drivers;
(11) Cleanup operation;
Summary: /sbin/init --> (/etc/inittab) --> Set the default run level --> Run the system initial script and complete system initialization --> Close Corresponding to the services that need to be closed, you need to start the service to start it --> Set up the login terminal
##CentOS 6:
The init program is: upstart, and its configuration file:
##/etc/inittab, /etc/init/*.conf
Note: The /etc/init/*.conf file syntax follows the upstart configuration file syntax format;
CentOS 6 startup process:
POST --> Boot Sequence(BIOS) -- > Boot Loader (MBR) --> Kernel(ramdisk) --> rootfs --> switchroot --> /sbin/init -->(/etc/inittab, /etc/init/*. conf) --> Set the default run level --> System initialization script --> Close or start services at the corresponding level --> Start terminal
##GRUB( Boot Loader):
grub: GRand Unified Bootloader
##grub 0.x: grub legacy
grub 1.x: grub2
##grub legacy:
stage1: mbr
stage1_5: The sector after mbr allows the bootloader in stage1 to identify the file system on the partition where stage2 is located;
password [--md5] STRING: Authentication when booting the selected kernel or operating system;
grub-md5-crypt command
Enter single-user mode:
(1) Edit the grub menu (select the title to be edited, and then use the e command);
(2) In the selected kernel It can be appended with
1, s, S or single;
(3) In the line where the kernel is located, type the "b" command;
Install grub:
(1) grub-install
grub-install --root-directory=ROOT /dev/DISK
##(2) grub
grub> root (hd#,#)
##grub> setup (hd#)
Linux Kernel:
Single-kernel system design, but fully draws on the advantages of the microkernel design system and introduces a modular mechanism to the kernel.
Kernel components:
kernel: Kernel core, usually bzIma, usually in the /boot directory, named vmlinuz-VERSION- RELEASE;
kernel object: Kernel object, generally placed in /lib/modules/VERSION-RELEASE/
[ ]: N
[M]: M
[*]: Y
Auxiliary file: ramdisk
initrd
initramfs
Running Kernel:
uname command:
##uname - print system information
uname [OPTION]...
-n: Display node name;
-r: Display VERSION-RELEASE;
Module:
lsmod command:
Display what has been done by the core The loaded kernel module
The displayed content comes from: /proc/modules file
modinfo command:
Display detailed description information of the module
Tool for generating kernel module dependency files and system information mapping files;
Loading or unloading kernel modules:
insmod command:
insmod [ filename ] [ module options... ]
##rmmod
rmmod [ modulename ]
/proc directory:
Kernel Its own internal status information and statistical information, as well as configurable parameters are output through the proc pseudo file system;
Parameters:
Read-only: Output information
Writable: User-specified "new value" can be accepted to configure a certain function or feature of the kernel
/proc/sys
(1) The sysctl command is used to view or set many parameters in this directory;
sysctl -w path.to.parameter=VALUE
~]# sysctl -w kernel.hostname=mail.madu.com
(2) The echo command can also modify the values of most parameters through redirection;
(2) Set by reading the configuration file Parameters
sysctl -p [/path/to/conf_file]
Route forwarding in the kernel:
/proc/sys/net/ipv4/ip_forward
Commonly used parameters:
net.ipv4.ip_forward
vm.drop_caches
kernel.hostname
/sys directory:
sysfs: Outputs the relevant attribute information of each hardware device recognized by the kernel, as well as the kernel’s setting information for hardware characteristics; Some parameters can be modified to adjust the hardware operating characteristics.
udev dynamically creates the required device files for each device through the information output under this path; udev is a user space program that runs; special tools: udevadmin, hotplug;
When udev creates a device file for a device, it will read its pre-defined rule files, usually in /etc/udev/rules.d and /usr /lib/udev/rules.d directory;
Production of ramdisk file:
(1) mkinitrd Command
Recreate the ramdisk file for the currently used kernel
Pass parameters to the kernel: append initrd=initrd.img ...
Mount the root file system and start anaconda
Start the GUI interface by default
If explicitly specified, use TUI Interface:
Just pass the "text" parameter to the kernel;
boot: linux text
Note: The above content should generally be located in the boot device; there are several ways to use subsequent anaconda and its installation packages:
Local CD
Local hard disk
ftp server: yum repository
http server: yum repostory
nfs server
If you want to manually specify the installation source:
boot: linux method
Working process of anaconda application:
Pre-installation configuration phase
Language used during the installation process
Keyboard type
Installation target storage device
Basic Storage: local disk
Special device: iSCSI
Set host name
Configure network interface
Time zone
Administrator password
Set partition mode and MBR installation location
Create a normal user
Select the program to be installed Package
Installation Phase
Create partitions on the target disk, perform formatting operations, etc.
Install the selected package to the target location
Install bootloader
First startup
iptables
selinux
core dump
anaconda configuration method:
(1) Interactive Configuration method;
(2) Automatically complete the configuration by reading the configuration file given in advance;
Configuration given according to specific syntax Options;
kickstart file;
##Installation boot options:
boot:
text: Text installation method
method: Manually specify the installation method to use
-n: Do not output the content in the mode to the screen;
-e: Multi-point editing;
-f /PATH/TO/SCRIPT_FILE: Read the editing script from the specified file;
-r: Supports the use of extended regular expressions;
-i: Edit in place;
Address delimitation:
(1) No address: process the full text;
(2) Single address:
#: The specified line;
/pattern/: Each line that can be matched by this pattern;
(3) Address range:
#,
##,+
#/pat1/,/pat2/
#,/pat1/
(4) ~:Step
1~2
2~2
Edit command:
d: Delete
p: Display the content in the pattern space
a \text : Append text after the line; support using \n to implement multi-line appending;
i \text: Insert text before the line; support using \n to implement multi-line insertion;
c \text: The replacement line is single or multi-line text;
w /path/to/somefile: Save the lines matched by the pattern space to the specified In the file;
r /path/from/somefile: Read the text stream of the specified file to the line after the matched line in the pattern space;
=: Print the line number for the line in the pattern space;
!: Negate the condition;
s/// : Support the use of other delimiters, s@@@, s;
replacement tag:
g: Inline global replacement;
p: Display the successfully replaced lines;
w /PATH/TO/SOMEFILE: Save the successful replacement results to the specified file ;
1: Delete the blank characters at the beginning of all lines starting with a blank in the /boot/grub/grub.conf file;
~]# sed 's@^[[:space:]]\+@@' /etc/grub2.cfg
2: Delete the # and blank characters at the beginning of all lines in the /etc/fstab file that begin with # and are followed by at least one blank character;
~]# sed 's@ ^#[[:space:]]\+@@' /etc/fstab
3: echo an absolute path to the sed command and extract its base name ;Get the directory name;
~]# echo "/etc/sysconfig/" | sed 's@[^/]\+/\?$@@'
Advanced editing commands:
h: Overwrite the content in the pattern space into the holding space;
H: Append the content in the pattern space to the holding space;
g: Take the data from the holding space and overwrite it into the pattern space;
G: Take out the content from the holding space and append it to the pattern space;
x: Exchange the content in the pattern space with the content in the holding space;
n: Read the next line of the matched line to the pattern space;
N: Append the next line of the matched line to the pattern space Space;
d: Delete lines in the pattern space;
D: Delete all lines in the multi-line pattern space;
sed -n 'n;p' FILE: Display even lines
sed '1!G;h;$!d' FILE: Display in reverse File content
sed '$!N;$!D' FILE: Take out the last two lines of the file;
sed '$!d' FILE: Take out the last line of the file;
sed 'G' FILE:
sed '/^$/d;G' FILE:
sed 'n;d' FILE: Display odd lines;
sed -n '1!G;h;$p' FILE: Display each line in the file in reverse;
bash script programming
##while CONDITION; do
Loop body
done
##Entry condition: CONDITION is true;
Exit condition: false
until CONDITION; do
Loop body
done
Entry condition: false
Exit condition: true
Example: Find the sum of all positive integers within 100;
#!/bin/bash
declare -i i=1
declare -i sum=0
until [ $i -gt 100 ]; do
let sum+=$i
let i++
done
##echo "Sum: $sum"
Example: Print the multiplication table
#!/bin/bash
#declare -i j=1
declare -i i=1
until [ $j -gt 9 ]; do
until [ $i -gt $j ]; do
echo -n -e "${i}X${j}=$[$i*$j]\t"
let i++
done
## echo
let i=1
let j++
done
Loop control statement (used in the loop body):
continue [N]: End the current cycle of layer N in advance and directly enter the next round of judgment;
while CONDTIITON1; do
CMD1
...
##if CONDITION2; then
continue
fi
CMDn
##...
done
break [N]: End the loop early;
while CONDTIITON1; do
CMD1
...
if CONDITION2; then
break
fi
CMDn
...
done
#Example 1: Find the sum of all even numbers within 100; it is required to loop through all positive integers within 100 ;
#!/bin/bash
declare -i i=0
declare -i sum=0
##until [ $i -gt 100 ]; do
let i++
## if [ $[$i%2] -eq 1 ]; then
continue
fi
let sum+=$i
done
echo "Even sum: $sum"
Create an infinite loop:
while true; do
Loop body
done
##until false; do
Loop body
done
Example 2 : Get information about logged-in users from the system every 3 seconds; if docker is logged in, it will be recorded in the log and exit;
#!/bin/bash
read -p "Enter a user name: " username
while true; do
if who | grep "^$username" &> /dev/null; then
##break
fi
sleep 3
done
echo "$username logged on." >> /tmp/user.log
Two implementations:
#!/bin/bash
read -p "Enter a user name: " username
##until who | grep "^$username" &> /dev/null; do
sleep 3
done
##echo "$username logged on." >> /tmp/user.log
Special usage of while loop (traverse each line of the file):
while read line; do
Loop body
##done < /PATH/FROM/SOMEFILE
Read each line in the /PATH/FROM/SOMEFILE file in turn, and assign the line value to the variable line:
Example: Find all users whose ID numbers are even numbers and display their user names and ID numbers;
Special format of for loop: for ((Control variable initialization; conditional judgment Expression; modified expression of control variable)); do
Loop body
done
Control variable initialization: only executed once when running into the loop code segment;
Corrected expression of the control variable: Control will be performed first at the end of each cycle Variable correction operation, and then make conditional judgment;
Example: Find the sum of all positive integers within 100;
#!/bin/bash
declare -i sum=0
for ((i =1;i<=100;i++)); do
let sum+=$i
done
echo "Sum: $sum."
##Example 2: Print the multiplication table;
#!/bin/bash
for((j= 1;j<=9;j++));do
for((i=1;i<=j;i++))do
echo -e -n "${i}X${j}=$[$i*$j]\t"
done
echo
done
(1) Display a menu as follows:
cpu) show cpu information;
mem) show memory information;
disk) show disk information;
quit) quit
(2) Prompt the user to select options;
(3) Display the user Selected content;
#!/bin/bash
#cat << EOF
##cpu) show cpu information;
mem) show memory information;
disk) show disk information;
quit) quit
========== ==================
##EOF
read -p "Enter a option: " option
while [ "$option" != 'cpu' -a "$option" != 'mem' -a "$option" ! = 'disk' -a "$option" != 'quit' ]; do
read -p "Wrong option, Enter again: " option
done
if [ "$option" == 'cpu' ]; then
## lscpu
elif [ "$option" == 'mem' ]; then
cat /proc/meminfo
elif [ "$option" == 'disk' ]; then
fdisk -l
else
echo "Quit"
exit 0
fi
Further:
The user selects and does not exit the script after the display is completed; instead, it prompts the user to continue to select and display other content; it does not exit until quit is used;
Conditional judgment: case statement
case variable reference in
PAT1)
Branch 1
##;;
PAT2)
Branch 2
##;;
...
*)
Default branch
;;
esac
Example:
#!/bin/bash
#cat << EOF
cpu) show cpu information;
mem) show memory information;
disk) show disk information;
quit) quit
==============================
EOF
read -p "Enter a option: " option
while [ "$option" != ' cpu' -a "$option" != 'mem' -a "$option" != 'disk' -a "$option" != 'quit' ]; do
read -p "Wrong option, Enter again: " option
done
##case "$option" in
cpu)
lscpu
;;
mem)
cat /proc/meminfo
##;;
disk)
fdisk -l
;;
*)
echo "Quit..."
exit 0
;;
esac
##(1) The script accepts parameters: start, stop, restart, status;
(2) If the parameter is not one of the four, prompt to use the format and then exit with an error;
(3) If it is start: create /var/lock/subsys/SCRIPT_NAME, and displays "Start successfully";
Consider: What should be done if it has been started once before?
(4) If it is stop: delete /var/lock/subsys/SCRIPT_NAME, and display "stop completed";
Consider : What should I do if it has been stopped beforehand?
(5) If it is a restart, stop first, then start;
Consider: What to do if there is no start?
(6) If it is status, then
If the /var/lock/subsys/SCRIPT_NAME file exists, "SCRIPT_NAME is running" will be displayed. ...";
If the /var/lock/subsys/SCRIPT_NAME file does not exist, "SCRIPT_NAME is stopped..." will be displayed;
Where: SCRIPT_NAME is the current script name;
##Summary: until, while, for, case
bash script programming:
case statement:
case Variable reference in
PAT1)
Branch 1
;;
PAT2)
Branch 2
;;
##. ..
##*)
branchn
;;
esac
case supports glob-style wildcards:
*: any character of any length ;
##?: Any single character;
[]: Any single character within the specified range;
a|b: a or b
function: function
Procedural programming: code reuse
Modular programming
Structured programming
Grammar 1:
function f_name {
...function body...
}
Syntax 2:
f_name() {
...Function body...
}
Call: The function will only be executed when it is called;
Call: Given a function name
Where the function name appears, it will be automatically replaced by the function code;
Life cycle of the function: Created when called, terminated when returned;
The execution result of the function is returned Value:
(1) Use the echo or print command for output;
(2) The execution result of the command called in the function body;
The exit status code of the function:
(1) The default depends on the exit status code of the last command executed in the function body;
(2) Custom exit status code:
return
The function can accept parameters:
Pass parameters to the function: When calling the function, just separate the given parameter list with a blank after the function name; for example, "testfunc arg1 arg2..."
In the function body, you can use $1, $2, ... to call these parameters; you can also use special variables such as $@, $*, $# ;
Print the NN multiplication table, using functions;
Variable scope:
Local variables: current shell process; in order to execute the script, a dedicated shell process will be started; therefore, the scope of local variables is the current shell script program file;
Local variables: the life cycle of the function; the variables are automatically destroyed when the function ends;
If there are local variables in the function, their names are the same as local variables;
Defining service control logic based on dependencies;
Core concept: unit
configuration file for identification and configuration; the file mainly contains system services, listening sockets, saved system snapshots and other init-related Information;
Save to:
/usr/lib/systemd/system
/ run/systemd/system
/etc/systemd/system
Unit type:
Service unit: The file extension is .service, used to define system services;
Target unit: The file extension is .target, used to simulate the implementation of " Runlevel";
Device unit: .device, used to define the device recognized by the kernel;
Mount unit: .mount, definition file System mount point;
Socket unit: .socket, used to identify the socket file used for inter-process communication;
Snapshot unit: . snapshot, management system snapshot;
Swap unit: .swap, used to identify swap devices;
Automount unit: .automount, file system Automatic mount point;
Path unit: .path, used to define a file or directory in the file system;
Key features:
Socket-based activation mechanism: socket and service program are separated;
Bus-based activation mechanism:
Device-based activation mechanism:
Path-based activation mechanism:
System snapshot: Save the current status information of each unit in a persistent storage device;
Backwards compatible with sysv init script;
Incompatible:
The systemctl command is fixed
systemctl cannot communicate with services that are not started by systemd
Management system service:
CentOS 7: service unit
Note: Compatible with earlier versions Service script
Command: systemctl COMMAND name.service
Start: service name start ==> systemctl start name.service
##Stop: service name stop ==> systemctl stop name.service
Restart: service name restart ==> systemctl restart name.service
Status: service name status ==> systemctl status name. service
Conditional restart: service name condrestart ==> systemctl try-restart name.service
Reload or restart the service: systemctl reload-or-restart name.service
Reload or conditionally restart the service: systemctl reload-or-try-restart name.service
Disable setting to auto-start at boot: systemctl mask name.service
Cancel prohibiting setting to auto-start at boot: systemctl unmask name.service
View the current activation status of a service: systemctl is-active name.service
View all activated services:
systemctl list-units --type service
View all services:
systemctl list -units --type service --all
The corresponding relationship of the chkconfig command:
Set a service to start Self-start: chkconfig name on ==> systemctl enable name.service
Disable: chkconfig name off ==> systemctl disable name.service
View the startup status of all services:
##chkconfig --list ==> systemctl list-unit-files --type service
Check whether the service starts automatically at boot: systemctl is-enabled name.service
##Other commands:
View service dependencies: systemctl list-dependencies name.service
Calling parameters in the function body: $1, $2, ...
$*, $@, $
#Pass parameters to the function:
Function name parameter list
systemd: System and Service
unit:
Type: service, target
.service, . target
systemctl
bash script programming:
##Array:
Variable: a memory space that stores a single element;
Array: a continuous memory space that stores multiple elements;
Array name
Index: The number starts from 0 and is a numerical index;
Note: Index is also supported Use custom formats, not just numerical formats;
bash arrays support sparse formats;
Reference elements in an array: ${ARRAY_NAME[INDEX]}
Declare an array:
declare -a ARRAY_NAME
declare -A ARRAY_NAME: Associative array;
Assignment of array elements:
(1) Only assign one element at a time;
ARRAY_NAME[INDEX]=VALUE
weekdays[0]=" Sunday"
weekdays[4]="Thursday"
(2) Assign all elements at once:
ARRAY_NAME=("VAL1" "VAL2" "VAL3" ...)
(3) Assign only specific elements:
ARRAY_NAME=([0]="VAL1" [3]="VAL2" ...)
(4) read -a ARRAY
Reference array element: ${ARRAY_NAME[INDEX]}
Note: Omitting [INDEX] means referencing the element with subscript 0;
The length of the array (the number of elements in the array): ${#ARRAY_NAME[*]}, ${#ARRAY_NAME[@]}
Example: Generate 10 random numbers and save them in an array, and find their maximum and minimum values;
#!/ bin/bash
declare -a rand
declare -i max=0
for i in {0..9}; do
rand[$i]=$RANDOM
echo ${rand[$i]}
## [ ${rand[$i]} -gt $max ] && max=$ {rand[$i]}
done
##echo "Max: $max"
Define an array. The elements in the array are all files ending with .log in the /var/log directory; statistics are required The sum of the number of lines in the file whose subscript is an even number;
#!/bin/bash
#declare -a files
files=(/var/log/*.log)
declare -i lines=0
for i in $(seq 0 $[${#files[*]}-1]); do
if [ $[$i%2] -eq 0 ];then
let lines+=$(wc -l ${files[$i ]} | cut -d' ' -f1)
fi
done
echo "Lines: $lines."
##Reference elements in the array:
All elements: ${ARRAY[@]}, ${ARRAY[*]}
Array slice: ${ARRAY[@] :offset:number}
offset: The number of elements to be skipped
number: The number of elements to be taken out, take the offset All elements after the amount: ${ARRAY[@]:offset};
Get the rightmost characters of the string: ${var: -lengh}
Note: after the colon There must be a blank character;
Get the substring based on the pattern:
${var#*word}: where word can be any specified character; function: from left to right, find the first occurrence of word in the string stored in the var variable, and delete all characters between the beginning of the string and the first occurrence of the word character;
${var##*word}: Same as above, but all content between the beginning of the string and the last character specified by word is deleted;
file="/var/log/messages"
${file##*/}: messages
${var%word*}: word can be any specified character; function: from right to left, find the first occurrence of word in the string stored in the var variable, and delete the string All characters between the last character to the left and the first word character;
file="/var/log/messages"
${file%/*}: /var/log
${var%%word*}: Same as above, except that the rightmost part of the string is deleted All characters between the characters on the side to the left and the last occurrence of word characters;
Example: url=:80
${url##*:}
${url%%:*}
Find Replacement:
${var/pattern/substi}: Find the first string matched by pattern in the string represented by var, and replace it with substi;
${var//pattern/substi}: Find all strings that can be matched by pattern in the string represented by var, and replace them with substi;
${var/#pattern/substi}: Find the string matched by pattern at the beginning of the line in the string represented by var, and replace it with substi;
${var/%pattern/substi}: Find the string matched by pattern at the end of the line in the string represented by var, and replace it with substi;
Find and delete:
${var/pattern}: Find the string represented by var and delete the first time The string matched by pattern
${var//pattern}:
${var/#pattern}:
${var/%pattern}:
##Character case conversion:
${var^^}: Convert all lowercase letters in var to uppercase;
${var,,}: Convert all uppercase letters in var to lowercase;
Variable assignment:
${var:-value}: If var is empty or not set, then return value; otherwise, return the value of var;
${var:=value}: If var is empty or not set, then return value and assign value to var; otherwise, return the value of var;
${var:+value}: If var is not empty, return value;
${var:?error_info}: If var is empty or not set, then return error_info; otherwise, return the value of var;
Use the configuration file for the script program:
(1) Define a text file and define "name=value" for each line
(2) Source this file in the script
Command:
mktemp Command:
mktemp [OPTION]... [TEMPLATE]
TEMPLATE: filename.XXX
XXX must appear at least three times;
OPTION:
-d: Create a temporary directory;
--tmpdir=/PATH/TO/SOMEDIR: Specify the location of the temporary file directory;
install command:
install [OPTION]... [-T] SOURCE DEST
install [ OPTION]... SOURCE... DIRECTORY
## install [OPTION]... -t DIRECTORY SOURCE...
install [ OPTION]... -d DIRECTORY...
Option:
- m MODE
##-o OWNER
-g GROUP
GNU awk:
Three tools for text processing: grep, sed, awk
grep, egrep, fgrep: text filtering tool; pattern
sed: line editor
Pattern space, hold space
awk: report generator, formatted text output;
AWK: Aho , Weinberger, Kernighan --> New AWK, NAWK
##GNU awk, gawk
gawk - pattern scanning and processing language
Basic usage: gawk [options] 'program' FILE ...
program: PATTERN{ACTION STATEMENTS}
Separate statements with semicolons
print, printf
Options:
-F: Specify the field separator used when inputting;
-v var=value: custom variable;
1, print
print item1, item2, ...
Key points:
(1) Comma Delimiter;
(2) Each output item can be a string or a numerical value; the field, variable or awk expression of the current record;
(3) If item is omitted, it is equivalent to print $0;
##2, variable
2.1 Built-in variables
FS: input field seperator, the default is blank characters;
OFS: output field seperator, the default is blank characters;
RS: input record seperator, newline character during input;
ORS: output record seperator, newline character during output;
NF: number of field, number of fields
{print NF}, {print $NF}
NR: number of record, number of lines;
FNR: Count each file separately; number of lines;
FILENAME: Current file name;
ARGC: Number of command line parameters;
ARGV : Array, which stores the parameters given by the command line;
2.2 Custom variables
( 1) -v var=value
Variable names are case-sensitive;
(2) Directly define
in the program. 3. Printf command
formatting Output: printf FORMAT, item1, item2, ...
(1) FORMAT must be given;
(2) There will be no automatic line wrapping, and the line wrapping control character needs to be explicitly given, \n
(3) In FORMAT, a formatting symbol needs to be specified for each subsequent item;
Format character:
%c: Display the ASCII code of the character;
%d, %i: Display decimal integer;
%e, %E: Display numerical value in scientific notation;
%f: Display as floating point number;
%g, %G: Display value in scientific notation or floating point form;
##% s: display string;
%u: unsigned integer;
##%%: display % itself;
Modifier:
#[.#]: The first number controls the width of the display; the second # represents the decimal point Precision;
(1) Any string can be used; the string must be Use double quotes;
(2) If an array element does not exist in advance, awk will automatically create this element when referencing it, and initialize its value to "empty string";
To determine whether an element exists in the array, use the "index in array" format;
##weekdays[mon]="Monday"
To iterate through each element in the array, use a for loop;
for(var in array) {for-body}
##~]# awk 'BEGIN{weekdays["mon"] ="Monday";weekdays["tue"]="Tuesday";for(i in weekdays) {print weekdays[i]}}'
Note : var will traverse each index of the array;
state["LISTEN"]++
state["ESTABLISHED"]++
~]# netstat -tan | awk '/^tcp\>/{state[$NF]++}END{for(i in state ) { print i,state[i]}}'
##~]# awk '{ip[$1]++}END{for(i in ip ) {print i,ip[i]}}' /var/log/httpd/access_log
1: Statistics of each file in the /etc/fstab file The number of times the system type appears;
~]# awk '/^UUID/{fs[$3]++}END{for(i in fs) {print i,fs[i ]}}' /etc/fstab
2: Count the number of occurrences of each word in the specified file;
~]# awk '{for(i=1;i<=NF;i++){count[$i]++}}END{for(i in count) {print i,count[i]}}' / etc/fstab
9, function
9.1 Built-in function
Numerical processing:
rand(): Returns a random number between 0 and 1;
String processing:
length([s]): Returns the length of the specified string;
sub(r, s,[t]): Use the pattern represented by r to find the matching content in the character represented by t, and replace its first occurrence with the content represented by s;
gsub(r,s,[t]): Use the pattern represented by r to find matching content in the character represented by t, and replace all occurrences of it with the content represented by s;
split(s,a[,r]): Use r as the separator to cut the character s, and save the cut result to the array represented by a;
~]# netstat -tan | awk '/^tcp\>/{split($5,ip,":");count[ip[1] ]++}END{for (i in count) {print i,count[i]}}'
Dependency resolution of YUM is a nightmare and was resolved in DNF with SUSE library ‘libsolv’ and Python wrapper along with C Hawkey.
YUM don’t have a documented API.
Building new features are difficult.
No support for extensions other than Python.
Lower memory reduction and less automatic synchronization of metadata – a time taking process.
The above is the detailed content of Basics of Linux System (2). For more information, please follow other related articles on the PHP Chinese website!
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn