Basics of Linux System (1)

PHP中文网
PHP中文网Original
2017-06-20 11:18:491826browse
Terminal:
Equipment that users must use to interact with the host;
Physical terminal: directly connected to the local monitor and keyboard device;/dev/console
Virtual terminal: attached to the physical Terminals that are virtualized by software on the terminal. CentOS 6 starts 6 virtual terminals by default
Ctrl+Alt+F#: [1,6]
Graphic terminal: A terminal implemented virtually in software that is attached to a physical terminal, but additionally provides a desktop environment;
Device file Path: /dev/tty
# Simulated terminal:
Command line interface opened under the graphical interface, based on ssh protocol or telnet protocol, etc. Remotely opened interface
Device file:/dev/pts/# [0,oo)
View the current terminal device: tty
Interactive interface: After starting the terminal, attach an interactive application to the terminal device
GUI:
X protocol, window manager, desktop
Desktop:
GNOME (C, gtk)
KDE (C++, qt)
XFCE (light Magnitude desktop)
CLI:
shell program:
sh (bourn)
csh
tcsh
ksh (korn)
bash (bourn again shell), GPL
zsh
Display the currently used shell:
# echo ${SHELL}
Display all shells used by the current system:
# cat /etc/shells
Command prompt: prompt
[root@localhost ~ ]
#[root@localhost ~]:PS1
prompt:
admin :
Normal user: $
Command:
Enter the command and press Enter:
prompt the shell program to find the executable program or code corresponding to the entered command, analyze it and submit it to the kernel to allocate resources to run it;
Represents one or more processes;
There are two types of commands that can be executed in the shell:
Built-in commands: brought by the shell and provided in a certain command form;
External commands: under a certain file system path of the current system There is a corresponding executable program file;
which, whereis
differentiates between internal or external commands:
# type COMMAND
Run command:
Command format:
COMMAND [OPTIONS...] [ARGUMENTS...]
Options: used to enable or disable one or more functions of the command ;
Short options: -c, for example: -l, -h
##Multiple short options can be used with the command, for example -l - h, can be written as -lh;
Long option: --word, for example: --long, --human-readable
Parameters : The action object of the command
provides data to the command;
Note:
1. Multiple options, as well as multiple parameters and commands should be separated by whitespace characters
2. Cancel command execution: Ctrl+c
##File system:
C:\Program files\office11\word\word.exe
##/etc/sysconfig/network-scripts/ifcfg-eth0
The file has two types of data:
Metadata: metadata
Data: data
1. File names are strictly case-sensitive; file1, File1, FILE1 are different files;
2. The file name can use any character except /, special characters are not recommended;
/: root directory, path separator;
3. The length of the file name cannot exceed 255 characters;
4. Therefore, files starting with . are all hidden files;
Path:
Absolute path: the path starting from the root directory;
Relative path: starting from the current location Path to the beginning;
Representation of the current location:
(1) ./: ./sysconfig/network-scripts
(2) Omit the above symbols: sysconfig/network-scripts
..: Indicates the upper-level directory of the current directory
Current directory: current directory, also called working directory;
pwd: printing working directory
LSB: Linux Standard Base
##Command summary: ls, cd, type, tty, cat , which, whereis, pwd, echo
Command:
(1) File system related:
Directory Management
File Management
File View
File editing
(2) System management related:
Getting Linux command help
External commands: There is an executable program located in a certain directory of the file system;
which, whereis
The path where the shell program searches for executable program files is defined in the PATH environment variable;
# echo $PATH
Note: From left to right
##Format: COMMAND [OPTIONS...] [ARGUMENTS...]
Internal command:
# help COMMAND
External command:
(1) # COMMAND --help
# COMMAND -h
(2) User manual (manual)
# man COMMAND
(3) Information page
info COMMAND
(4) Help document of the program itself
README
INSTALL
ChangeLog
(5) Program official documentation
Official site: Documentation
(6) Official documentation of the distribution
(7) Google
Internal command help :
help COMMAND
##hash command:
shell The path results of the searched external commands will be cached in kv (key-value) storage;
history command:
Manage command history;
When logging in to the shell, the commands recorded in the command history file will be read: ~/.bash_history
The newly executed command after logging in to the shell is only Will be recorded in the cache; these commands will be "appended" to the command history file when the user exits;
history:
-a: Append the history list of newly executed commands in this session to the history file;
-d: Delete the specified command in the history;
-c: Clear command history;
Quick operation:
!#: Call history The #th command;
!string: the most recent command starting with string in the call history;
!!: the previous command
External command help acquisition:
(2) man COMMAND
Man page:/usr/share/man
man1 ... man8
man1: User command
man2: System call
man3: C library call
man4: Device file and special file
man5: Configuration file format
man6: Game
man7: Miscellaneous
man8: Management commands
Note: Some keys have help manuals in more than one chapter;
To view the manual in the specified chapter: man # COMMAND
The configuration file of the man command: /etc/man.config
MANPATH /PATH/TO/SOMEWHERE: Specify the search location for new manual files
# man -M /PATH/TO/SOMEWHERE COMMAND: Search the manual page for the COMMAND command at the specified location and display it;
## Paragraph description in the help manual:
NAME
SYNOPSIS
DESCRIPTION
OPTIONS
EXAMPLES
AUTHOR
REPORTING BUGS
SEE ALSO
SYNOPSIS:
[]:Optional content
<> ;: Required content
a|b: Choose one of the two
##...: The same content can appear multiple times
Man command operation method:
Space, ^V, ^f, ^F: scroll to the end of the file;
b, ^B: Scroll to the beginning of the file;
d, ^D: Scroll to the end of the file;
u, ^U: Go half the screen to the beginning of the file;
RETURN, ^N, e, ^E or j or ^J: Go to the end of the file Turn one line;
y or ^Y or ^P or k or ^K: Turn one line to the beginning of the file;
q: Exit;
#: Jump to line #;
1G: Return to the beginning of the file
G: Go to the end of the file
Text search:
/KEYWORD:
Using the string specified by KEYWORD as the keyword, search from the current position to the end of the file; the characters are not case-sensitive;
n: Next A
N: Previous
?KEYWORD:
The string specified by KEYWORD As a keyword, search from the current position to the beginning of the file; characters are not case-sensitive;
n: Same direction as the search command, next
N: In the opposite direction to the search command, the previous
(3) info
info COMMAND
(4) Help document of the program itself
/usr/share/doc/ COMMAND-VERSION
(5) Official program documentation
(6) Release version Official documentation
##(7) Google
(8) slideshare
Basic commands:
date:
date [OPTION]... [+FORMAT]: Display
FORMAT: Format symbol
%D
%F
%T
date [MMDDhhmm[[CC] YY][.ss]]: Settings
MM: Monthly minute
DD: What day
hh: hour
mm: minute
YY: two digit year
CCYY: Four-digit year
.ss: Seconds
# Two kinds of clocks in Linux:
System clock: Timing performed by the Linux kernel through the working frequency of the CPU;
Hardware clock:
hwclock: Display the hardware clock
-s, --hctosys
-w, --systohc
# #cal: Calendar
Directory-related commands:
Current directory or working directory
Home directory, home directory: HOME
root: /root
##Normal user: /home/USERNAME
/home/tom
~: The user’s home directory
cd:
##cd or cd ~: Return to the current user’s home directory
cd ~USERNAME: Switch to the specified The user’s home directory
cd -: Switch back and forth between the previous directory and the current directory
.
..
Related environment variables:
PWD: The current directory path is saved;
OLDPWD: The last directory path;
pwd: Display the current directory
ls: list
Display the file list under the specified path;
ls [OPTION]... [DIR]...
-a, --all: Display all files, including hidden files;
-l: Long format
-rw-r--r-- 1 root root 44800 Aug 14 14:32 install.log
-rw-r--r--:
The first digit on the left: File type
-, d, l, b, c, p, s
The next 9 digits: access permission, perm
Number: The number of times the file has been hard linked;
Left root: The owner of the file
Right root : File group
44800: File size
##Aug 14 14:32 : File last modified time
install.log: File name
-h, --human-readable:Unit conversion
## -d: Display related attributes of the directory itself; usually used with -l;
-r, --reverse: Display
## in reverse order #-R, --recursive: Recursive
##stat /PATH/TO/SOMEFILE: Get the specified file Metadata
File viewing command: cat, tac
cat [OPTION]... [FILE] ...
-E: Display the line terminator $
-n: Number each line displayed
File content type view command: file
file /PATH/TO/SOMEWHERE
Echo command: echo
-n: disable automatic addition of newline characters;
-e: allow Use escape characters;
\n: line break
\t: tab character
echo "$VAR_NAME": Variables will be replaced, double quotes represent weak references
echo '$VAR_NAME': Variables will not be replaced, strong references
which: Display the program file path corresponding to the command
which [OPTION] COMMAND
--skip-alias: Suppress display of aliases
whatis:
Use the mkwhatis command to change the current All help manuals on the system and their corresponding keywords are created as a database;
System management commands:
Shutdown:
halt, poweroff, shutdown, init 0
Restart:
reboot, shutdown, init 6
Related to user login:
##who, whoami, w
Linux file system:
Root file system (rootfs):
root filesystem
LSB, FHS: (FileSystem Heirache Standard)
/etc, /usr, /var, /root, /home , /dev
/boot: The directory where boot files are stored. Kernel files (vmlinuz) and boot loaders (bootloader, grub) are stored in this directory;
/bin: Basic commands for all users; cannot be associated with independent partitions, programs that will be used when the OS starts;
/ sbin: basic commands for management; cannot be associated with independent partitions, and is a program that will be used when the OS starts;
/lib: basic shared library files, and kernel module files (/lib /modules);
/lib64: The storage location of auxiliary shared library files dedicated to x86_64 systems;
/etc: Configuration file directory (Plain text file);
/home/USERNAME: ordinary user’s home directory;
/root: administrator’s home directory;
/media: Portable mobile device mount point;
cdrom
usb
/mnt: temporary file system mount point;
/dev: device file and special file storage location;
b: block device, random access
c: character device, linear access
/opt: The installation location of third-party applications;
/srv: Data used by services running on the system;
/tmp: Temporary file storage location;
/usr: universal shared, read-only data;
bin: Application program provided to ensure that the system has complete functions;
sbin:
lib:
lib64:
include: C program header files;
share: structured independent data, such as doc, man, etc.;
local: installation location of third-party applications;
##bin, sbin, lib, lib64, etc, share
/var: variable data files
cache: application cache data directory;
lib: application status information data;
local: dedicated to storing variable data for applications under /usr/local;
lock: lock file
log: log directory and file;
opt: specially used for /opt The application stores variable data;
run: data related to the running process; usually used to store the pid file of the process;
spool: application data pool;
tmp: saves temporary data generated between two system restarts;
/proc: A virtual file system used to output kernel and process information;
/sys: A virtual file system used to output information related to hardware devices on the current system;
/selinux: security enhanced Linux, the storage location of selinux-related security policies and other information;
Applications on Linux Components:
Binary programs: /bin, /sbin, /usr/bin, /usr/sbin, /usr/local/bin, /usr/local/sbin
Library files: /lib, /lib64, /usr/lib, /usr/lib64, /usr/local/lib, /usr/local/lib64
Configuration files: /etc, /etc/DIRECTORY, /usr/local/etc
##Help files: /usr/share/man, /usr/share/doc, /usr/local/share/man, /usr/local/share/doc
File type under Linux:
- (f): Ordinary file;
d: Directory file;
b: Block device;
c: Character device;
l: Symbolic link file;
p: Pipe file;
s: Socket file; socket;
System management commands:
Shutdown:
halt, poweroff, shutdown, init 0
Restart:
reboot, shutdown, init 6
Related to user login:
##who, whoami, w
Shut down or restart:
halt, poweroff
reboot
-f: Force, do not call shutdown
-p: Cut off the power supply
shutdown:
shutdown [OPTION]... TIME [MESSAGE]
##-r: reboot
-h: halt
-c: cancel
TIME:
now: Immediately
+m: Relative time representation, how long after the command submission; for example +3;
hh:mm: Absolute time representation, specify the specific time;
User login information viewing command:
whoami: Displays the currently logged in valid users;
who: All current login sessions in the system;
w: All current login sessions and operations performed by the system;
Basic features of bash (1):
(1) Command history
history
##Environment variables:
HISTSIZE: The number of command history records;
HISTFILE: ~/.bash_history;
##HISTFILESIZE: The number of history records recorded in the command history file Number;
history -d OFFSET
##-c
history #: Display the latest # commands in the history;
-a: Manually append the command history of the current session buffer to the history file;
Calling commands in history:
!#: Repeat the #th command;
!! :
!string
Calling the last parameter of the previous command:
!$:
ESC, .
Alt+.
Control the recording method of command history:
Environment variable: HISTCONTROL
ignoredups: Ignore duplicate commands; consecutive and identical methods For "repeat";
ignorespace: ignore all commands starting with a blank;
ignoreboth:ignoredups, ignorespace;
How to modify the environment variable value: export variable name="value"
Variable assignment: store the data after the assignment symbol in The variable name points to the memory space;
(2) Command completion
bash execution command:
Internal commands:
External commands: bash searches each path from left to right according to the path defined by the PATH environment variable and names the given command name file, the first time it is found is the command to be executed;
Direct completion: Tab, the string given by the user has only one unique corresponding command ;
If the corresponding command starting with the string given by the user is not unique, Tab will give a list again;
(3) Path completion
Treat the string given by the user as the beginning of the path, and search for file names starting with the specified string in the specified parent directory ;
If unique: then complete directly;
Otherwise: Tab again to give the list;
(4) Command line expansion
~: Expand to the user’s home directory
~USERNAME : Expand to the home directory of the specified user
{}: Can host a comma-separated list and expand it into multiple paths
/tmp/{a,b} = /tmp/a, /tmp/b
/tmp/{tom,jerry}/hi = /tmp/tom/hi, / tmp/jerry/hi
(5) Command execution result status
Success
Failed
bash uses the special variable $? to save the execution status result of the latest command:
0: Success
1-255: Failure
There are two types of results of program execution:
The return value of the program;
The execution status result of the program;
Directory management commands:
cd, pwd, ls
mkdir, rmdir, tree
mkdir [options] /path/to/somewhere
-p: exists without error and can automatically create the required directories;
-v : Display detailed information
-m MODE: Directly specify permissions when creating a directory;
tree:
-d: Display only directories
-L level: Specify the number of levels to display
-P pattern: Only display paths matched by the specified pattern;
rmdir: Delete empty directories
rmdir [OPTION ]... DIRECTORY...
-v: Display process;
Text file viewing class command:
cat, tac
more, less, tail, head
more
more [OPTIONS...] FILE...
-d: Display page turning and exit prompts
less
##less [OPTIONS...] FILE...
head
head [OPTION]... [FILE]...
-c #: Specify to get the first #byte
-n #: Specify to get the previous # lines
-#:
tail
tail [OPTION]... [FILE]...
-c #: Specify the # words after retrieval Section
-n #: Specify the # line after getting
-#:
- f: Track and display the newly appended content of the file;
File timestamp management tool:
touch
File: metadata, data
View file status: stat
Three timestamps:
access time: access time, abbreviated as atime, read file content
modify time: modification time, mtime , change the file content (data)
change time: change time, ctime, metadata changes
touch Command:
touch [OPTION]... FILE...
-a: only atime
-m: only mtime
##-t STAMP:
## [[CC]YY]MMDDhhmm[.ss]
-c: If the file does not exist, it will not be created
File system:
boot, bin, sbin, lib, lib64, dev, home, root, mnt, media, etc, proc, sys
usr
var
Basic features of bash:
Command completion
Path completion
Command history
Command line expansion:
~, {}
Status result of command
Success: 0
Failure: 1-255
Directory management: mkdir, rmdir
##File viewing: more, less, tail, head
Time stamp management: touch
-a, -m, -t
-c
File management:
cp, mv, rm
Copy command: cp
cp [ OPTION]... [-T] SOURCE DEST
        cp [OPTION]... SOURCE... DIRECTORY
            cp [OPTION]... -t DIRECTORY SOURCE...
cp SRC DEST
SRC is the file:
If the target does not exist: create a new DEST, And fill the content in SRC into DEST;
If the directory exists:
If DEST is a file: overwrite the content in SRC to In DEST;
It is recommended to use the -i option for the cp command at this time;
If DEST is a directory: Create a new file with the original file under DEST file with the same name, and fill the contents of SRC into the new file;
cp SRC... DEST
SRC...: Multiple files
DEST must exist and be a directory, otherwise an error will occur;
cp SRC DEST
SRC is the directory:
Use option at this time: -r
##If DEST is not Exists: Create the specified directory and copy all the files in the SRC directory to DEST;
If DEST exists:
If DEST is a file: Error
         
If DEST is a directory:
        Common options:  
       
-i: Interactive
-r, -R: Recursively copy the directory and all contents inside;
-a: Archive, equivalent to -dR -- preserv=all
-d:--no-dereference --preserv=links
--preserv[=ATTR_LIST]
     
mode: Permissions
       
ownership: Owner group
         
timestamp:  
links
                                                                                                    ​ ##      
-p: --preserv=mode,ownership,timestamp
       
-v:  -verbose
                   
-f: --force
mv: move, move file
mv [OPTION]... [-T] SOURCE DEST
mv [OPTION]... SOURCE... DIRECTORY
mv [OPTION]... -t DIRECTORY SOURCE...
Common options:
#-i: Interactive
-f: Force
rm: remove, delete
rm [OPTION]... FILE...
Commonly used options:
-i: Interactive
-f: Forced deletion
-r: Recursive
rm -rf
Text editor: nano
Full screen editor
Basic features of bash (2):
1. Command alias (alias)
Achieved through the alias command:
(1) alias
Displays all available command aliases for the current shell process;
(2) alias NAME='VALUE'
Define the alias NAME, which is equivalent to executing the command VALUE;
Note: The alias defined in the command line is only valid for the current shell process; if you want it to be permanently valid, it must be defined in the configuration file;
Only for the current user: ~/.bashrc
Valid for all users: /etc/bashrc
Note: The new configuration given by editing the configuration will not take effect immediately;
The bash process re-reads the configuration file:
source /path/to/config_file
##. /path/to/config_file
##Undo alias: unalias
unalias [-a] name [name ...]
Note: If the alias is the same as the name of the original command, If you want to execute the original command, you can use "\COMMAND";
2. glob (globbing)
Used in bash to implement "wildcarding" of file names
Wildcard characters: *, ?, []
(1) *
Any characters of any length
a*b:
aab, ab, a123b,
abc
(2) ?
Any single character
a?b:
aab
ab, a12b, abc
(3) []
Match any single character within the specified range
[0-9]
##[a-z]:Characters are not case-sensitive
( 4) [^]
matches any single character outside the specified range
##[^0-9]
Special character set:
[:digit:]: any number, equivalent to 0-9
[:lower:]: Any lowercase letter
[:upper:]: Any uppercase letter
[:alpha:] : Any uppercase and lowercase letters
[:alnum:]: Any numbers or letters
[:space:]:
[:punct:]: Punctuation marks
3. Bash shortcut keys
Ctrl+l: Clear the screen, equivalent to the clear command;
##Ctrl+a: Jump to the beginning of the command;
Ctrl+e: Jump to the end of the command;
Ctrl+c: Cancel the execution of the command;
Ctrl+u: Delete everything from the beginning of the command line to the location of Guangcun;
Ctrl+k: Delete the cursor Everything from the location to the end of the command line;
4, bash’s I/O redirection and pipeline
Program: Instruction + Data
Read data: Input
Output data: Output
Every open file has a fd: file descriptor (file descriptor)
Standard input: keyborad, 0
Standard output: monitor, 1
Standard error output: monitor, 2
I/O Redirection: Change Standard Position
##Output Redirection: COMMAND > NEW_POS, COMMAND >> NEW_POS
>: Overwrite redirection, the original content in the target file will be cleared;
>>: Append weight Orientation, the new content will be appended to the end of the target file;
# set -C: prohibits overwriting the content into the existing file;
Force override:>|
# set +C:
##2> : Overwrite the redirection error output data stream;
##2>>: Append the redirection error output data stream;
Standard output and error output are each directed to different locations:
##COMMAND > /path/to/file.out 2> /path/to/error.out
Merge standard output and error output into the same data stream for redirection:
&>: Override redirection
&>>:Append redirection
#COMMAND > /path/to/file.out 2> &1
COMMAND >> /path/to/file.out 2>> &1
Input redirection :<
tr command: Convert or delete the characters
tr [OPTION]... SET1 [SET2 ]
##HERE Documentation:<<
# cat << EOF
# cat > /path/to/somefile << EOF
Pipeline:
COMMAND1 | COMMAND2 | COMMAND3 |...
Note: The last command will be executed in the sub-shell process of the current shell process;
tee command:
tee [OPTION]... [FILE]...
Text processing tools: wc, cut, sort, uniq
##wc command:
wc [OPTION]... [FILE]...
-l: lines
-w: words
-c: characters
cut command:
cut [OPTION].. . [FILE]...
-d DELIMITER: Specify the delimiter
-f FILEDS:
#: The #th field
#,#[,#]: multiple discrete fields, such as 1,3,6
#-#: Multiple consecutive fields, such as 1-6
Mixed use: 1-3,7
--output-delimiter=STRING
sort command:
sort [OPTION] ... [FILE]...
-f: Ignore character case
##-r: Reverse order
-t DELIMITER: Field delimiter
-k #: Sort based on the specified field
-n: Sort by numerical size
-u: uniq, remove duplicates after sorting
uniq command:
uniq [OPTION]... [FILE]...
-c: Display the number of times each line appears repeatedly;
-d: Only display repeated lines;
-u: Only display unique lines;
Note: Consecutive and identical squares are duplicates
User and Group Management
Resource allocation:
Authentication:Authentication
Authorization:Authorization
##Accouting:Audit
Audition
token, identity(username/password)
Linux user: Username/UID
Administrator: root, 0
Normal user: 1-65535
System users: 1-499, 1-999
Allocate permissions to the daemon process to obtain resources;
Login users: 500+, 1000+
Interactive login;
Linux group: Groupname/GID
Administrator group: root, 0
Normal group:
System group: 1 -499, 1-999
Normal group: 500+, 1000+
Linux security context:
Running program: process
Run as the process initiator:
root: cat
tom: cat
All resources that the process can access The permissions depend on the identity of the initiator of the process;
Linux group category:
The user’s basic group (Main group):
The group name is the same as the user name and contains only one user: Private group
Additional group for the user (additional group ):
Linux user and group related configuration files:
/etc/passwd: Users and their attributes Information (name, UID, basic group ID, etc.);
/etc/group: Group and its attribute information;
/etc /shadow: User password and its related attributes;
/etc/gshadow: Group password and its related attributes;
/etc/passwd:
##name:password:UID:GID:GECOS:directory:shell
Username: Password: UID: GID: GECOS: Home directory: Default shell
##/etc/group:
group_name:password:GID:user_list
Group name:Group password:GID: User list with current group as additional group (separator is comma)
/etc/shadow
Username: Encrypted Password: Date of last password change: Password Minimum usage period: Maximum password usage period: Password warning period: Password ban period: Account expiration date: Reserved field
Encryption mechanism:
Encryption: plain text--> cipher text
Decryption: cipher text--> plain text
##One-way encryption: extract data fingerprint
md5: message digest, 128bits
sha1: secure hash algorithm, 160bits
sha224: 224bits
sha256: 256bits
sha384: 384bits
sha512: 512bits
Avalanche effect: Small changes in initial conditions will cause huge changes in the results ;
Fixed-length output:
Password complexity policy:
1. Use at least 3 types of numbers, uppercase letters, lowercase letters and special characters;
2. Be long enough;
3. Use a random password;
4. Change it regularly; do not use the password you have used recently;
User and group related management commands:
User creation: useradd
useradd [options] LOGIN
-u UID: [UID_MIN , UID_MAX], defined in /etc/login.defs
##-g GID: Indicates the basic group to which the user belongs, which can be a group name or a GID;
-c "COMMENT": User's comment information;
-d /PATH/TO/HOME_DIR: Use the specified path as the home directory;
-s SHELL: Specify the user's default shell program, the available list is in the /etc/shells file;
-G GROUP1[,GROUP2,... [,GROUPN]]]: Specify additional groups for the user; the group must exist in advance;
-r: Create a system user
CentOS 6 : ID<500
CentOS 7: ID<1000
##Default value setting: /etc/default/ In useradd file
useradd -D
-s SHELL
Group creation: groupadd
groupadd [OPTION]... group_name
-g GID: Specify the GID number ;[GID_MIN, GID_MAX]
##-r: Create system group;
CentOS 6: ID<500
CentOS 7: ID<1000
View user-related ID information: id
id [OPTION]... [USER]
-u: UID
-g: GID
-G: Groups
-n: Name
Switch users or execute commands as other users :su
su [options...] [-] [user [args...]]
How to switch users:
su UserName: Non-login switching, that is, the target user’s configuration file will not be read;
su - UserName: Login switching, will read the target user's configuration file; complete switching;
#Note: No password is required for root su to other users; non-root users A password is required when switching;
Change the identity and execute the command:
su [-] UserName -c 'COMMAND'
Options:
-l: "su -l UserName" is equivalent to "su - UserName"
User attribute modification: usermod
usermod [OPTION] login
-u UID: New UID
-g GID: New Basic Group
-G GROUP1[,GROUP2, ...[,GROUPN]]]: New additional group, the original additional group will be overwritten; if you retain the original one, you must also use the -a option, which means append;
-s SHELL: New default SHELL;
-c 'COMMENT': New comment information;
-d HOME: New home directory; files in the original home directory will not be moved to the new home directory at the same time; if you want to move, use the -m option at the same time;
-l login_name: new Name;
-L: lock specified user
-U: unlock specified user
-e YYYY-MM-DD: Specify the user account expiration date;
#-f INACTIVE: Set the inactivity period;
Add a password to the user: passwd
passwd [OPTIONS] UserName: Modify the password of the specified user, only root user permissions
passwd: Change your password;
Commonly used options:
-l: Lock the specified user
-u: Unlock the specified user
-n mindays: Specify the minimum usage period
-x maxdays: The maximum usage period
-w warndays: how many days in advance to start warning
-i inactivedays: inactive period;
--stdin: Receive user password from standard input;
echo "PASSWORD" | passwd --stdin USERNAME
Note: /dev/null, bit buckets
/dev/zero,
Delete user: userdel
userdel [OPTION]... login
-r: Delete user home directory;
Group attribute modification: groupmod
groupmod [OPTION]... group
-n group_name: New name
-g GID: New GID;
Group deletion: groupdel
groupdel GROUP
Group password: gpasswd
##gpasswd [OPTION] GROUP
-a user: Add user to the specified group;
-d user: Delete user user’s current group Additional group for the group name
-A user1,user2,...: Set the list of users with administrative rights
newgrp command: Temporarily switch the basic group;
If the user does not belong to this group, the group password is required;
Modify user attributes: chage
chage [OPTION]... LOGIN
-d LAST_DAY
-E, --expiredate EXPIRE_DATE
##-I, --inactive INACTIVE
-m, --mindays MIN_DAYS
-M, --maxdays MAX_DAYS
-W, --warndays WARN_DAYS
Other commands: chfn, chsh, finger
##Command summary: useradd, groupadd, su, id, usermod, userdel, groupmod, groupdel, passwd, newgrp, pwck, gpasswd, chage, chsh, chfn, finger
Permission management:
File permissions are mainly defined for three types of objects:
owner: owner, u
group: belonging group, g
other: other, o
Each file is for each type of access Everyone has defined three permissions:
r: Readable
w: Writable
x: eXcutable
File:
r: You can use file viewing tools to obtain its content;
w: Its content can be modified;
x: This file can be submitted to the kernel to start as a process;
Directory:
r: You can use ls to view the file list in this directory;
w: You can Create files in this directory and delete files in this directory;
x: You can use ls -l to view the file list in this directory, and you can cd to enter this directory;
--- 000 0
--x 001 1
-w- 010 2
-wx 011 3
r-- 100 4
r-x 101 5
rw- 110 6
rwx 111 7
For example:
640: rw-r-----
rwxr-xr-x: 755
Modify file permissions: chmod
chmod [OPTION]... OCTAL-MODE FILE...
-R: Recursively modify permissions
chmod [OPTION]... MODE[,MODE]... FILE...
MODE:
Modify all permissions of a type of user:
u=
g=
o=
##ug=
a=
u=,g=
Modify one or more permissions of a type of user
u+
u-
##chmod [OPTION].. . --reference=RFILE FILE...
Refer to the permissions of the RFILE file and modify the FILE to the same as RFILE;
Modify the owner and group of the file:
Only available to root;
Modify the file's owner Owner: chown
chown [OPTION]... [OWNER][:[GROUP]] FILE...
Usage:
OWNER
OWNER:GROUP
##:GROUP
Note: The colon in the command can be replaced;
-R: Recursion
chown [OPTION]... --reference=RFILE FILE...
Modify the file's group: chgrp
chgrp [OPTION]... GROUP FILE...
chgrp [OPTION]... --reference=RFILE FILE...
-R
Mask code when creating a file or directory :umask
FILE: 666-umask
Note: If there is x permission in the result of the permission reduction of a certain type of user, then +1
DIR: 777-umask
##umask: View
umask #: Settings
Command summary: chmod, chown, chgrp, umask
##File management, user management, permission management, basic features of bash
File management: cp, mv, rm
User management:
useradd, usermod, chsh, chfn, chage, userdel
##groupad, groupmod, groupdel
passwd, gpasswd, pwck
id, finger, who, whoami, w
su
Configuration files: /etc/passwd, /etc/shadow, /etc/group, /etc/gshadow
Permission management:
perm: mode(rwxrwxrwx), ownership
chmod
chown
chgrp
-R, --reference=RFILE
FILE: 666-umask
DIR: 777-umask
umask [UMASK]
Bash basic features:
Command line expansion: ~, {}
##Command alias: alias/unalias
Command history: history
Command and path completion: $PATH
glob: *, ? , [], [^]
Shortcut keys: Ctrl+{a,e,l,c,u,k}
##Command hash :hash
Basic features of bash (3)
1. Provides a programming environment
Program: instructions + data
Program programming style:
Procedural formula: Instruction is the center, and data serves the instruction
Object-based: Data is the center, and the instruction serves the data
Shell program: Provides programming capabilities and explains how to execute the
program:
Computer: Run binary instructions ;
Programming language:
Low-level: Assembly
High-level:
Compilation: High-level language-->Compiler-->Object code
##C, C++, java
Explanation: High-level language-->Interpreter-->Machine code
shell, perl, python
Procedural programming:
Sequential execution
Loop execution
Select execution
Shell programming: procedural, interpreted execution
Basic structure of programming language:
Data storage: variables, arrays
Expression
Statement
shell script: text file
shebang:
!/bin/bash
#!/usr/bin/python
#!/usr/bin/perl
magic number: magic number
Run the script:
1. Give execution permission , specify file execution through a specific file path;
2. Run the interpreter directly and run the script as a parameter of the interpreter program;
Variables:
Named memory space;
Data storage method: ASCII
Character: 110: 24
Value: 110 --> 8
Integer
Floating point type
Variable: Variable type
Function :
1. Data storage format;
2. Participating operations;
3 , represented data range;
Type:
Characters
Value:
Integer type
Floating point type
Programming programming language:
Strong type:
Weak type: bash
Put all the required The stored data are all treated as characters
Floating point numbers are not supported;
Logical operations:
true, false
1, 0
##with:
1 && 1 = 1
1 && 0 = 0
0 && 1 = 0
0 && 0 = 0
or:
1 || 1 = 1
1 || 0 = 1
0 || 1 = 1
0 || 0 = 0
Not:
! 1 = 0
! 0 = 1
##Short circuit operation:
And:
The first one is 0, the result must be 0;
The first one is 1, the second one must be Participate in the operation;
or:
The first one is 1, the result must be 1;
The first one is 0, and the second one must participate in the operation;
grep:
Text Processing Three Musketeers on Linux
grep: text filtering (pattern) tool;
grep, egrep, fgrep
sed: stream editor, text editing tool;
awk: implementation of gawk on Linux, text report generator;
grep: Global search REgular expression and Print out the line.
Function: text search tool, based on the user-specified "pattern" to match the target text line by line; print out the match to the line;
Pattern: filter conditions written by regular expression characters and text characters;
REGEXP: composed of a special type Patterns written by characters and text characters, some of which do not represent the literal meaning of the characters, but represent control or wildcard functions;
is divided into two categories:
Basic regular expression: BRE
Extended regular expression: ERE
grep -E, egrep
Regular expression engine
##grep [OPTIONS] PATTERN [FILE...]
Options:
--color=auto: Color the matched text;
-v: Display lines that cannot be matched by pattern;
-i: Ignore character case;
-o: Only display the matched string;
-q: Silent mode, no information is output;
-A #: after, after # lines
-B #: before, before # lines
-C #: context, before and after # lines
-E: Use ERE;
##Basic regular expression metacharacters:
Character matching:
.: Matches any single character;
[]: Matches within the specified range Any single character
[^]: Matches any single character outside the specified range
[:digit:], [:lower: ], [:upper:], [:alpha:], [:alnum:], [:punct:], [:space:]
##Number of matches: Used after the character to be specified a number of times, used to specify the number of times the previous character is to appear;
*: Match the previous character any number of times;
For example: grep "x*y"
abxy
xay
xxxxxxy
Greedy mode
.*: Any character of any length;
\?: Matches the preceding character 0 or 1 times; that is, the preceding character is optional;
\+: Matches the preceding character characters at least once;
\{m\}: Match the previous character m times;
\{m,n\}: Match the previous character at least m times, At most n times;
\{0,n\}: Match the previous character at most n times;
\{m,\} : Match the previous character at least m times;
Position anchoring:
^: Beginning of line anchoring; Used for the far left side of the pattern;
$: end-of-line anchoring; used for the far right side of the pattern;
^PATTERN$ : Used to pattern match the entire line;
^$: Empty line;
^[[:space:]]*$
\< or \b: word-initial anchor; used on the left side of the word pattern;
\> ; or \b: word ending anchor; used for the right side of the word pattern;
\: matches the entire word;
Grouping:
\(\): Bundle one or more characters together and process them as a whole;
\(xy\)*ab
Note: The content matched by the pattern in the grouping brackets will be recorded by the regular expression engine Among the internal variables, the naming method of these variables is: \1, \2, \3, ...
\1: starting from the left, the first opening bracket And the characters matched by the pattern between the right brackets;
\(ab\+\(xy\)*\):
\1: ab\+\(xy\)*
\2: xy
Back reference: Reference the characters matched by the pattern in the preceding grouping brackets (not the pattern itself)
If user root exists, display its default shell Program;
id root &> /dev/null && grep "^root\>" /etc/passwd | cut -d: -f7
Find the two or three digits in /etc/passwd;
grep "\<[0-9]\ {2,3\}\>" /etc/passwd
Display /etc/rc.d/rc.sysinit file, starting with at least one blank Lines starting with characters and followed by non-blank characters;
# grep "^[[:space:]]\+[^[:space:]]" /etc/grub2 .cfg
Find the lines ending with 'LISTEN' followed by 0, 1 or more blank characters in the results of the "netstat -tan" command;
# netstat -tan | grep "LISTEN[[:space:]]*$"
Add user bash, testbash, basher and nologin (its shell is /sbin/nologin); then find the line in the /etc/passwd file where the user name is the same as the shell name;
grep "^\([ [:alnum:]]\+\>\).*\1$" /etc/passwd
Write a script to implement the following functions
If user1 exists, display its existence, otherwise add it;
Display the ID number and other information of the added user;
#!/bin/bash
##id user1 &> /dev/null && echo "user1 exists." || useradd user1
id user1
egrep and extended regular expressions
##egrep = grep - E
egrep [OPTIONS] PATTERN [FILE...]
##Extended regular expression Metacharacters of the formula:
Character matching:
.
[]
[^]
Number of matches:
##*
?: 0 or 1 times;
+: 1 or more times;
{m}: Match m times;
{m,n}: at least m, at most n times;
Anchor:
^
##$
\<, \b
\>, \b
##Group:
()
Backreferences: \1, \2, ...
Or:
a|b
##C|cat: C or cat
1. Display the current The default shell and UID of the system root, centos or user1 user;
# grep -E '^(root|centos|user1)\>' /etc/passwd | cut -d : -f1,3,7
2. Find a word in the /etc/rc.d/init.d/functions file (centos6) followed by A line of parentheses;
# grep -E -o "^[_[:alpha:]]+\(\)" /etc/rc.d/init.d /functions
3. Use echo to output an absolute path, and use egrep to get its base name;
# echo "/mnt/sdc" | grep -E -o "[^/]+/?$" | cut -d"/" -f1
further Ground: Use egrep to get the directory name of the path, similar to the result of the dirname command;
4. Find the value between 1-255 in the ifconfig command result ;
5. Find the IP address in the ifconfig command result;
fgrep : Does not support regular expression search;
Basic features of bash (4)
Variable type:
Data storage format, storage space size, participating operation types;
Character type
Numeric type:
Integer type
Floating point type
Strong typing: The type must be specified when defining a variable, and the type must meet the type requirements when participating in operations; calling undeclared variables will generate an error;
Weak type: No need to specify the type, the default is character type; implicit type conversion will be automatically performed when participating in the operation; variables can be called directly without being defined in advance;
bash
Types of variables in bash:
According to standards such as the effective range of variables:
Local variables: the effective scope is the current shell process; it is invalid for other shell processes other than the current shell, including subshell processes of the current shell;
Environment variables: effective The scope is the current shell process and its sub-processes;
Local variables: the effective scope is a certain code fragment (usually a function) in the current shell process;
Position variables: $1, $2, ... are used to allow the script to call the parameters passed to it through the command line in the script code;
Special variables: $ ?, $0, $*, $@, $
#Local variable:
Variable assignment: name= 'value'
## can be quoted:
value:
(1) can be Direct string; name="username"
(2) Variable reference: name="$username"
(3) Command reference : name=`COMMAND`, name=$(COMMAND)
Variable reference: ${name}, $name
"": Weak reference, the variable reference will be replaced with the variable value;
'': Strong reference, the variable reference will not be replaced with the variable value, but the original string will be retained;
Display all defined variables
set
Destroy variables:
unset name
Environment variables:
Variable declaration and assignment:
export name=VALUE
##declare -x name=VALUE
Variable reference: $name, ${name}
Display all environment variables:
export
env
printenv
Destroy:
unset name
bash has many built-in environment variables: PATH, SHELL, UID, HISTSIZE, HOME, PWD, OLD, HISTFILE, PS1
Variable naming rules:
1. Do not use reserved words in the program: such as if, for;
2. Only numbers, letters and underscores can be used, and cannot start with a number;
3. Know the name by name,
Read-only variable:
readonly name
declare -r name
Position variable:
Call the parameters passed to the script through the command line in the script code;
$1, $2, ...: correspond to the first and second parameters of the call;
shift [n]
$0: The command itself;
##$*: All parameters passed to the script;
$@: All parameters passed to the script;
$#: The number of parameters passed to the script;
Example: Determine the number of lines in the given file
#!/bin/bash
linecount="$(wc -l $1| cut -d' ' -f1)"
echo "$1 has $linecount lines."
bash configuration file:
##Divided according to the effective scope, there are two categories:
Global configuration:
/etc/profile
##/etc/profile.d/*.sh
/etc/bashrc
Personal configuration:
~/.bash_profile
~/.bashrc
Divided by function, there are two categories:
profile class: Provide configuration for interactive login shell
Global:/etc/profile, /etc/profile.d/*.sh
Personal: ~/.bash_profile
Function:
(1) Used to define environment variables;
(2) Run a command or script;
bashrc class: Provide configuration for non-interactive login shell
Global:/etc/bashrc
Personal:~/.bashrc
##Function:
(1) Define command alias;
(2) Define local variable;
Shell login:
Interactive login:
Log in directly through the terminal by entering the account and password;
Use "su - UserName" or "su -l UserName" to switch users
##/etc/profile --> / etc/profile.d/*.sh --> ~/.bash_profile --> ~/.bashrc --> /etc/bashrc
Non-interactive login:
su UserName
Terminal opened under the graphical interface
Execute script
~/.bashrc --> /etc/bashrc --> /etc/profile.d/*.sh
How the new configuration defined by editing the configuration file takes effect:
(1) Restart the shell process;
(2) Use source or .command process;
Question:
1. Define an alias that is effective for all users?
2. Add one more path to the user's PATH environment variable, for example, /usr/local/apache2/bin
administrator?
all?
Arithmetic operations in bash
##+, -, *, /, %, **
Implement arithmetic operations:
(1) let var=arithmetic expression
(2) var=$[arithmetic expression]
(3) var=$((arithmetic expression))
(4) var=$(expr arg1 arg2 arg3...)
Multiplication symbols need to be escaped in some scenarios;
bash has a built-in random number generator: $RANDOM
Enhanced assignment:
+=, -=, *=, /=, %=
##let varOPERvalue
For example: let count+=1
Increase and decrement:
let var+=1
let var++
let var-=1
let var- -
Calculate the sum of the IDs of the 10th user and the 20th user in the /etc/passwd file;
#!/bin/bash
##userid1=$(head -n 10 /etc/passwd | tail -n 1 | cut -d: -f3 )
userid2=$(head -n 20 /etc/passwd | tail -n 1 | cut -d: -f3)
useridsum=$[$userid1+$userid2]
##echo "uid sum: $useridsum"
Pass two file paths as parameters to the script and calculate the sum of all blank lines in the two files;
# !/bin/bash
##spaceline1=$(grep "^[[:space:]]*$" $1 |
wc - l)
spaceline2=$(grep "^[[:space:]]*$" $2 |
wc -l)
echo "The sum of space line: $[$spaceline1+$spaceline2]"
Statistics/etc, / How many first-level subdirectories and files are there in the var, /usr directories;
Conditional test:
Determining whether a certain requirement is met needs to be implemented by the testing mechanism;
Note: Special test expressions need to be assisted by test commands to complete the testing process. ;
Test command:
test EXPRESSION
##[ EXPRESSION ]
[[ EXPRESSION ]]
##Note: There must be blank characters before and after EXPRESSION;
bash test type:
Numerical test:
-gt: Is it greater than ;
-ge: Whether it is greater than or equal to;
-eq: Whether it is equal to;
-ne: whether it is not equal to;
-lt: whether it is less than;
-le: whether it is less than or equal to;
String test:
==: whether it is equal to;
>: Whether it is greater than;
<: Whether it is less than;
!=: Whether it is not Equal;
=~: Whether the string on the left can be matched by the PATTERN on the right;
Note: This expression is generally used In [[ ]];
-z "STRING": Test whether the string is empty, if it is empty, it is true, if it is not empty, it is false;
-n "STRING": Test whether the string is not empty. If it is not empty, it is true, if it is empty, it is false;
Note: use All operands used in string comparisons should be quoted;
File Test
bash custom exit status code
exit [n]: Custom exit status code;
Note: Once in the script When encountering the exit command, the script will terminate immediately; the termination exit status depends on the number after the exit command;
Note: If no exit status code is specified for the script, The exit status code of the entire script depends on the status code of the last command executed in the script;
Accepts a file path as a parameter;
If the number of parameters is less than 1, the user will be prompted "at least one parameter should be given" and exit immediately;
If the number of parameters is not less than 1, the user will be prompted The number of blank lines in the file pointed to by the first parameter;
egrep, extended regular expression, variable, configuration file, arithmetic operation, conditional test, exit status code
ERE:
Character matching: ., [], [^]
Number of matches: *, ?, +, {m,n}
Position anchoring: ^, $, \<, \>, \b
Group: (), \1, \2, ..
or: a|b
##Variables:
Local variables
Environment variables
Local variables
Position variables
Special variables
Reserved words cannot be used;
Commands: unset, export, declare -x, set, env, printenv, readonly
Profile:
profile, bashrc
##Arithmetic operations:
let, $[], $(()), expr
##+=, -=, *=, /=
++, --
Conditional test:
test, [], [[]]
Three types:
Value: -lt, - le, -gt, -ge, -ne, -eq
Strings: ==, !=, >, <, =~, -z, -n
File
##Custom exit code:
exit [n]
##[ $# -lt 1 ] && echo "At least one argument." && exit 1
vim editor
Introduction
vi: Visual Interface, text editor
Text: ASCII, Unicode
##Text editing type:
Line editor: sed
Full screen editor: nano, vi
##VIM - Vi IMproved
Using
vim: Modal editing
Basic mode:
Edit mode, command mode
Input mode
Last line mode:
Built-in command line interface
Open the file:
# vim [OPTION]. .. FILE...
+#: After opening the file, place the cursor directly at the beginning of line #;
##+/ PATTERN: After opening the file, place the cursor directly at the beginning of the first line matched by PATTERN;
Mode conversion:
Edit mode--> Input mode
i: insert, input at the cursor position;
a: append, enter after the cursor position;
o: open a new line below the current cursor position;
I: in Enter at the beginning of the line where the current cursor is;
A: Enter at the end of the line where the current cursor is;
O: Enter at the end of the line where the current cursor is Open a new line above the current line;
c
C
Input mode--> Edit mode
ESC
##Edit mode--> Last line mode
:
Last line mode --> Edit mode
ESC
##Close file:
:q Exit
:q! Force quit and discard the changes;
:wq Save and exit
:x Save and exit
:w /PATH/TO/SOMEWHERE
##ZZ: Save and exit;
Cursor jump:
Jump between characters:
h, j, k, l
h: left
#l: right
j : Down
##k: Up
COMMAND: Jump to the number of characters specified by #;
Jump between words:
w: The beginning of the next word
e: The ending of the current or next word
b: The beginning of the current or previous word
#COMMAND: The number of words to jump at one time is specified by
#Jump at the beginning and end of the line:
^: jump to the first non-blank character at the beginning of the line;
0: jump to the beginning of the line;
##$ : Jump to the end of the line;
Move between lines:
#G: Jump to the point specified by # Row;
##G: the last row;
1G, gg: the first row;
Moving between sentences:
)
(
Moving between paragraphs:
}
{
vim editing command:
Character editing:
x: Delete the character at the cursor;
#x: Delete the # characters starting at the cursor;
xp: Swap the characters at the cursor and the position of the following characters;
Replacement command (r, replace)
r: Replace the character where the cursor is
Delete command:
d: Delete command, which can be combined with cursor jump characters to achieve range deletion;
d$:
d^:
d0:
dw
de
db
#COMMAND
dd: Delete the line where the cursor is located ;
dd: Multi-line deletion;
##Paste command (p, put, paste):
p: If the buffer stores a whole line, paste it below the line where the current cursor is; otherwise, paste it behind the current cursor position;
P: If the buffer contains a whole line, paste it above the line where the current cursor is; otherwise, paste it in front of the current cursor position;
Copy command (y, yank):
y: Copy, the working behavior is similar to the d command;
y$
y0
y^
##ye
yw
yb
COMMAND
yy: Copy rows
#yy: Copy multiple rows;
Change command (c, change)
c: Modify
edit mode--> input mode
c$
c^
##c0
cb
ce
cw
#COMMAND
cc: Delete and enter new content
#cc:
Other editing operations
Visual mode:
v: Select by character
V: Line by line
Note: Often combined with editing commands;
d, c, y
Undo the previous edit:
u(undo): Undo the previous edit Operation;
#u: Undo the specified number of operations;
Undo the previous undo:
Ctrl+r
Repeat the previous editing operation:
.
Screen flip operation:
Ctrl+f: Scroll to the end of the file;
Ctrl+b: Scroll one screen to the beginning of the file;
##Ctrl+d: Scroll half a screen to the end of the file;
Ctrl+u: Turn half the screen to the beginning of the file;
Last line mode in vim:
Built-in command line interface
(1) Address delimitation
:start_pos ,end_pos
#: The specific # line, for example, 2 means line 2;
#,#: # means the line from the left Starting, to the right # represents the end of the line;
#,+#: Starting from the line represented by # on the left, plus the number of lines represented by # on the right;
.: Current line
$: Last line
.,$-1
%: Full text, equivalent to 1,$
##/pat1/,/pat2/:
Start from the line matched by pat1 pattern for the first time to the end of the line matched by pat2 for the first time;
#,/pat/
/pat/,$
Usage:
followed by An edit command
d
##y
w /PATH/TO/SOMEWHERE: Change the range Save the lines in the specified file to the specified file;
r /PATH/FROM/SOMEFILE: Insert all the contents of the specified file at the specified location;
(2) Search
/PATTERN: Search from the current cursor position to the end of the file;
? PATTERN: Search from the current cursor position to the beginning of the file;
n: The same direction as the command;
N: The opposite direction to the command;
(3) Find and replace
s: Complete the find and replace operation in the last line mode
s/What to find/What to replace with/Modifiers
What to find: You can use the pattern
Replaced content: Patterns cannot be used, but backward reference symbols such as \1, \2, ... can be used; "&" can also be used to refer to the entire content found during the previous search;
Modifiers:
i: Ignore case
g: Global replacement; by default , only replace the first occurrence in each line;
Find the delimiter in the replacement/can be replaced with other characters, such as
s@@@
s
##1. Copy /etc/grub2. cfg to the /tmp/ directory, and use the search and replace command to delete the blank characters at the beginning of the line in the /tmp/grub2.cfg file;
%s/^[[:space:]] \+//g
2. Copy the /etc/rc.d/init.d/functions file to the /tmp directory, and use the find and replace command to /tmp Add a # sign at the beginning of each line of /functions that starts with a blank character;
:%s/^[[:space:]]/#&/
Multiple file mode:
vim FILE1 FILE2 FILE3 ...
:next next
:prev previous
:first first
: last the last
:wall save all
:qall exit all
Window separation mode:
vim -o|-O FILE1 FILE2 ...
-o : Horizontal split
-O: Vertical split
## Switch between windows: Ctrl+w, Arrow
Single file window split:
Ctrl+w,s: split, horizontal split
Ctrl+w,v: vertical, vertical split
Customize the working characteristics of vim:
Configuration file: permanently valid
Global:/etc/vimrc
##Personal:~/.vimrc
Last line: The current vim process is valid
(1) Line number
Display: set number, abbreviated as set nu
Cancel display: set nonumber, abbreviated as set nonu
(2) Bracket matching
Match: set showmatch, abbreviated as set sm
Cancel: set nosm
(3) Automatic indentation
Enable: set ai
Disable: set noai
(4) Highlight search
Enable: set hlsearch
Disable: set nohlsearch
(5) Syntax highlighting
Enable: syntax on
Disable: syntax off
(6) Ignore the case of characters
Enable: set ic
Do not ignore: set noic
Get help:
:help
:help subject
bash condition test:
## Test method:
test EXPRESSION
[ EXPRESSION ]
[[ EXPRESSION ]]
Categories of test expressions:
Numerical comparison
String test
File test:
Existence test
-a FILE
- e FILE: File existence test, if it exists, it is true, otherwise it is false;
Existence and category test
-b FILE: Whether Exists and is a block device file;
-c FILE: Whether it exists and is a character device file;
-d FILE: Whether it exists and It is a directory file;
-f FILE: exists and is an ordinary file;
-h FILE or -L FILE: exists and is Symbolic link file;
-p FILE: whether it exists and is a named pipe file;
-S FILE: whether it exists and is a socket Word file;
File permission test:
-r FILE: Whether it exists and is readable
-w FILE: Whether it exists and is writable
-x FILE: Whether it exists and is executable
File special permission test:
-g FILE: Whether it exists and has sgid permission;
-u FILE: Whether it exists and has suid permission;
-k FILE: Whether it exists and has sticky permission;
File size test:
-s FILE: Whether it is saved and not empty;
Whether the file is open:
-t fd: fd indicates whether the file descriptor is open and connected to a terminal Related
-N FILE: Whether the file has been modified since it was last read;
-O FILE: Whether the current valid user is the file owner;
-G FILE: Whether the current valid user is the file owner;
Binocular test:
FILE1 -ef FILE2: Whether FILE1 and FILE2 point to the same inode on the same device
FILE1 -nt FILE2: Whether FILE1 is newer than FILE2;
FILE1 -ot FILE2: Whether FILE1 is older than FILE2;
Combined test conditions:
Logical operation:
First way:
COMMAND1 && COMMAND2
COMMAND1 || COMMAND2
! COMMAND
[ -e FILE ] && [ -r FILE ]
##Second way:
EXPRESSION1 -a EXPRESSION2
EXPRESSION1 -o EXPRESSION2
! EXPRESSION
Must use the test command;
# [ -z "$hostName" -o "$hostName"= ="localhost.localdomain" ] && hostname www.madu.com
# [ -f /bin/cat -a -x /bin/cat ] && cat /etc/fstab
vim:
Edit mode, input mode, last line mode, visualization mode
Jump: h,j,k,l,w,b,e,),(,},{, G, ^, 0, $
Edit: x, r, c, d, y, p, u, ctrl+r
Search: /, ?, n, N
Find and replace: s
s///
g:
i:
Last line demarcation:
#m,n
m,+
#.
$
/pat1/
/pat1/,/pat2/
%
File test:
Single eye: -e, -f, -d, -b, -c, -L, - P, -S, -r, -w, -x, -s
Binary: -nt, -ot
Combination test: -a, -o, !
File search:
In the file system Find files that meet the conditions;
File search: locate, find
Non-real-time search (database search) :locate
Real-time search: find
##locate:
Relies on a pre-built index; the index is built automatically when the system is idle (periodic tasks); the database is updated manually (updatedb);
Index The build process needs to traverse the entire root file system, which consumes a lot of resources;
Working features:
The search speed is fast;
Fuzzy search;
Non-real-time search;
locate KEYWORD
find:
Real-time search tool, completes file search by traversing the file system under the specified path;
Working characteristics:
The search speed is slightly slow;
Accurate Search;
Real-time search;
Syntax:
find [OPTION]... [Search path] [Search conditions] [Processing action]
Search path: specify the specific target path; the default is the current directory;
Search conditions: The specified search criteria can be based on file name, size, type, permissions and other criteria; the default is to find all files under the specified path;
Processing Action: What to do on files that meet the conditions; output to the screen by default;
Search conditions:
Based on File name search:
-name "file name": supports the use of glob
##*, ?, [], [^]
-iname "File name": Insensitive to case letters
##-regex "PATTERN": Match the entire PATTERN File path string, not just file name;
Search based on owner and group:
-user USERNAME: Search for files whose owner is the specified user;
group GRPNAME: Search for files whose owner is the specified group;
-uid UserID: Find the file whose owner is the specified UID number;
#-gid GroupID: Find the file whose owner is the specified UID number Files with GID numbers;
-nouser: Find files without owners;
-nogroup: Find There are no files belonging to the group;
Search based on file type:
-type TYPE:
f: Ordinary file
d: Directory file
l: Symbolic link file
s: Socket file
b: Block device file
c: Character device file
p: Pipe file
Combined conditions:
and: -a
or: -o
Non: -not, !
## !A -a !B = !(A -o B)
!A -o !B = !(A -a B)
Find the files in the /tmp directory whose owner is not root and whose file name is not fstab;
find /tmp \( -not -user root -a -not -name 'fstab' \) -ls
find /tmp -not \( -user root -o -name 'fstab' \) -ls
Search based on file size:
-size [+|-]#UNIT
Commonly used units: k, M, G
UNIT: (#-1, #]
## -#UNIT:[0,#-1]
+#UNIT: (#,oo)
According to the timestamp:
## in "days";
-atime [+|-]#,
#: [#,#+1)
+#: [#+1,oo]
- #: [0,#)
-mtime
-ctime
In "minutes":
##-amin
-mmin
## -cmin
Search based on permissions:
-perm [/|-]MODE
MODE: Exact permission matching
/MODE: As long as one of the permissions of any type (u, g, o) object can be matched;
-MODE: Each type of object must also have the permission standards specified for it;
Processing action:
-print: the default processing action, displayed on the screen;
-ls: ​​similar to executing "ls -l" on the found file "Command;
-delete: delete the found file;
-fls /path/to/somefile: all the found files Save the long format information to the specified file;
##-ok COMMAND {} \; Execute the command specified by COMMAND for each file found;
Before executing the command for each file, the user will be interactively asked for confirmation;
-exec COMMAND {} \; Execute the command specified by COMMAND for each file found. Command;
{}: used to reference the found file name itself;
Note: find is passed When the found files are passed to the later specified command, all the found files that meet the conditions are passed to the subsequent commands at once;
Some commands cannot accept too many parameters, and the command execution may fail; another way to avoid this problem is:
find | xargs COMMAND
1. Find all files or directories under the /var directory whose owner is root and whose group is mail;
# find /var -user root -group mail
2. Find all files or directories in the /usr directory that do not belong to root, bin or hadoop;
# find /usr -not -user root -a -not -user bin -a -not -user hadoop
find / usr -not \( -user root -o -user bin -o -user hadoop \)
3. Find the week in the /etc directory. The content has been modified, and the owner is not root, nor is it a hadoop file or directory;
# find /etc -mtime -7 -a -not -user root -a -not -user hadoop
# find /etc/ -mtime -7 -a -not \( -user root -o -user hadoop \)
4. Find files or directories that have no owner or group on the current system and have been accessed in the last week;
# find / -nouser -a -nogroup -a -atime -7
5. Find all files in the /etc directory that are larger than 1M and are of normal file type;
# find /etc -size +1M -type f
6. Find the /etc directory All users under the directory do not have write permissions for files;
# find /etc -not -perm /222
7. Find at least one type of file in the /etc directory that the user does not have execution permissions;
# find /etc -not -perm -111
8. Find files in the /etc/init.d directory that all users have execution permissions and other users have write permissions;
# find / etc/init.d -perm -113
Special permissions on Linux file systems
##SUID, SGID, Sticky
1 Permissions
r, w, x
##user, group, other
2 Security context
Prerequisite: The process has an owner and Belongs to a group; a file has an owner and a group;
(1) Whether any executable program file can be started as a process depends on whether the initiator has execution permissions on the program file;
(2) After it is started as a process, the owner of the process is the initiator; the group of the process is the group to which the initiator belongs;
(3) The permissions of a process when accessing a file depend on the initiator of the process:
#(a) If the initiator of the process is the same as the owner of the file: the file owner permissions apply ;
(b) The initiator of the process belongs to the file's group; then the file group permissions apply;
(c) Application File "Other" permissions;
3 SUID
(1) Whether any executable program file can be started As a process: It depends on whether the initiator has execution permission on the program file;
(2) After starting as a process, the owner of the process is the owner of the original program file;
Permission settings:
chmod u+s FILE...
chmod u-s FILE...
4 SGID
By default, when a user creates a file, its attributes The group is the basic group to which this user belongs;
Once a directory is set with an SGID, the group to which the files created in this directory by users with write permissions belong. The group of this directory;
Permission settings:
chmod g+s DIR...
chmod g-s DIR...
5 Sticky
For a directory writable by multiple people, if sticky is set, each user can only delete his or her own files;
Permission settings:
chmod o+t DIR...
##chmod o-t DIR...
SUID SGID STICKY
000 0
001 1
010 2
011 3
100 4
101 5
110 6
111 7
##chmod 4777 /tmp/ a.txt
Several permission bit mappings:
SUID: user, occupies the owner’s execution permission bit ;
s: The owner has x permissions
S: The owner does not have x permissions
SGID: group, occupies the execution permission bit of group;
s: group has x permissions
S: group does not have x permissions
Sticky: other, occupies the execution permission bit of ohter;
t: other has x permissions
T: other does not have x permission
bash script programming:
Procedural programming Language:
Sequential execution
Selective execution
Loop execution
Select execution:
if Judgment condition
then
The condition is true branch code
fi
##if judgment condition; then
The branch code where the condition is true
else
The branch code where the condition is false
fi
##

The above is the detailed content of Basics of Linux System (1). For more information, please follow other related articles on the PHP Chinese website!

Statement:
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