Linux Uncle Bird's private kitchen study notes

Linux

6.3.3 Data extraction

headfetch the first few lines

head -n 20Take the first 20 lines,
head -n -100except the last 100 lines, and take out all the front lines

tailFetch the next few lines

tail -n 20Fetch the last 20 lines,
tail -n +100only list the data after 100 lines,
tail -fand continue to detect the file content

6.3.4 Non-plain text files od

od -t [acdfox]

a: default character output;
c: ASCII character output
d decimal f floating point o octal x hexadecimal

6.3.5 touch to modify the file time or create a new file

touch [-acdmt]

-a revision accesstime only; -m modificationtime; -c file time;
touch -d "2 day ago" bashrctwo days ago
touch -t 201506150202the modification date was 2015/06/15 2:02


6.4 Default and hidden permissions for files and directories

chown chmod

6.4.1 File default permission umask

umask: 022 (default
setting method: umask 002
file permission = 666 - umask = 644 = rw-r–r–
directory permission = 777 - umask = 755 = rwxr-xr-x

Need to pay attention to the situation of umask=003, at this time umask=--- --- -wx file permissions should be 666-umask = (rw-rw-rw-) - (-------wx) = rw -rw-r-- is 664 and if only calculated by numbers, 666-003=663, which is rw-rw--wx, and the x permission appears out of thin air, which is inconsistent with the facts

6.4.2 File hidden attributes chattr, lsattr

chattr [+-=][ASacdistu]

a: The file can only add data, but cannot delete or modify data
i: The file cannot be deleted, renamed, set a link, and cannot write or add data

lsattr [-adR]

-a: display hidden attributes
-d: directory
-R: list the data of China Unicom subdirectory together

6.4.3 File special permissions SUID, SGID, SBIT

SUID: Set UID
s on the permissions of the file owner

1. Only valid for binary bin
2. The executor must have x permission
3. Only valid at runtime
4. The executor will have owner permission

For example, all account passwords in linux are recorded in the /etc/shadow file. The permissions of this file are --------- 1 root root means that only root can modify it, but we can use the passwd command when we use the general account user Modify the password by yourself 1. user has x permission to the program /usr/bin/passwd, 2. the owner of passwd is the account root 3. user will temporarily obtain root permission during the process of executing passwd 4. /etc/shadow can Passwd modification performed by user

SGID: Set GID
When the s flag is in the x item of the file group, it is the SGID, but the SGID can be set for files and directories.
to the file:

1. Valid for binary bin
2. The executor must have x permission
3. The executor will get the support of the program group when executing

to the file:

1. When the user has r and x permissions for this directory, the user can enter this directory
2. The effective group of the user in this directory will become the group of this directory
3. Purpose: If the user When this directory has w permissions (files can be created), the created file group is consistent with the directory group

SBIT: Stiky Bit
Currently only valid for directories:

1. When the user has the w, x permission of the directory, that is to say, he has the permission to write.
2. When the user creates a file or directory under the directory, only he and root have the right to delete the file

The permission settings of SUID, SGID, and SBIT are respectively recorded as 421, which need to be added before the original 755,
such as adding SUID, chmod 4755 filename

6.4.4 Observe file type file

file filename

6.5 Command and Document Search

6.5.1 Searching for command file names

which [-a] command
which is to search for the specified directory in PATH, like the built-in history of bash cannot be found, you can use the type command

6.5.2 File name search

whereis [-bmsu] nameSearch only in a specific directory
locate [ir] keywordUse the database to search
find [PATH] [option] [action]Search the hard disk (the slowest and hard disk-consuming method, the last used)
find / -name "*file*"

6.6 Relationship between permissions and commands

cdUsers need at least x permissions
cat more lessfor directories, at least
nano vix permissions for directories,
cp /dir1/file1 /dir2and at least r permissions for files. At least w, x permissions are required for dir2

6.7 Review review

ls [-dal]Very important

-d list only the directory itself
-a list all files together with hidden files
-l list long data strings

There are three types of recording time for files: access time (atime), status time (ctime), and modification time (mtime)
umaskto regulate the default permissions of new files
page338 Example
SUID SGID SBITUsage

7 Linux disk and file system management

7.2 Simple operation of the file system

7.2.1 Capacity of disks and directories

  • df: List the overall disk usage of the file system
  • du: Evaluate the disk usage of the file system (commonly used to estimate the capacity of the directory)

df [-ahikHTm]
a: all. h: easy to read. km: unit. i: inode.
du [-ahskm]
a: all. h: easy to read. s: List the total amount, not the individual categories. S: Totals under subdirectories are not included.

7.2.2 Entity links and symbolic links: ln

  • The contents of the file are pointed to by the inode
  • To read a file, the file name recorded in the directory must point to the correct inode number to read

ln /etc/crontabThe Hrad Link entity link is that the file name is connected to the same inode, so everything is the same except for the file name. But it can't cross Filesystem, and can't link directory. (pointing to the inode of data)
ln -s /etc/crontab crontab2Symbolic Link The symbolic link creates an independent file, which will allow the reading of data to point to the file name of the file he linked. (pointing to the inode of the data file name)

7.3 Disk partitioning, formatting, verification and mounting

Steps when adding a hard disk:
1. Partition the disk and create an available partition
2. Format the partition (format) to create an available filesystem
3. You can check the filesystem just created
4. Required on Linux systems Create a mount point, which is a directory, and mount it

7.3.1 Observing the disk partition status

lsblkList all disks on the system (list blok device)
blkidList device UUID and other parameters
partedList disk partition table type and partition information ( parted /dev/sda print)

7.3.2 Disk partition gdis/fdisk

  • Create a new partition gdisk /dev/sdacommand: n
    partprobe -sUpdate the partition table information of the Linux kernelcat /proc/partitions

  • Use gidsk to delete a partition command: d

7.3.3 Disk formatting (creating a file system)

mkfs make filesystem

  • xfs filesystem mkfs.xfs
    mkfs,xfs [-b bsize] [-d parms] [-i parms] [-L label] [-f] [-r parms] 设备名称

7.3.4 File verification system

xfs_repair [-fnd] 设备名称Handles xfs filesystems.
fsck.ext4 [-pf] [-b superblock] 设备名称Handle EXT4 file system

7.3.5 Mounting and unmounting of file system

  • A single file system should not be mounted repeatedly in different mount points (directories);
  • A single directory should not repeatedly mount multiple file systems;
  • The directory to be used as the mount point should theoretically be an empty directory. (If it is not empty, the original content in the directory will disappear temporarily)

mount -a
mount [-l]
mount [-t 文件系统] LABEL='' 挂载点
mount [-t 文件系统] UUID='' 挂载点
mount [-t 文件系统] 设备文件名='' 挂载点

Mount xfs, etc.

blkid /dev/sda4
mkdir /data/xfs
mount UUID="0aea968b7c0c" /data/xfs
df /data/xfs

mount disc

blkid /dev/sr0
mkdir /data/cdrom
mount /dev/sr0 /data/cdrom
df /data/cdrom

mount U disk

blkid /dev/sda1
/dev/sda1:UUID="35BC-6D6B" TYPE="vfat"
/dev/sda1
mkdir /data/usb
mount -o codepage=950,iocharset=utf8 UUID="35BC-6D6B" /data/usb
df /data/	usb

Remount the root directory and mount an unspecified directory
. When the root directory appears read-only, you can restart the machine or use mount -o remount,rw,auto
the options and parameters of -o mount, xx. Remounting is a very important mechanism, especially When entering single-player maintenance mode.

Uninstall the device file
umount [-fn]
-f force unloading, which can be used in situations where the network file system NFS cannot be read
-l unload the file system immediately, better than -f -n
unload without updating /etc/mtab

7.3.6 Disk/filesystem parameter revisions

Modify the Label name or journal parameters.

mknod 设备文件名 [bcp] [Major] [Minor]
b: Set the device name as a peripheral storage device, such as a disk, etc.
c: Set the device name as a peripheral input device, such as a keyboard and mouse, etc.
p: Set the device name as a FIFO file

xfs_admin [-lu] [-L label] [-U uuid]Modify the UUID and Label name of the XFS file system, and forget to add the header name when formatting. You can use this command to process the LABEL name and UUID when you want to add it again.

tune2fs [-l] [-L label] [-U uuid]Modify the label name and UUID of ext4

7.4 Set boot mount

7.4.1 Mount /etc/fstab and /etc/mtab on boot

filesystem table :
[设备/UUID等] [挂载点] [文件系统] [文件系统参数] [dump] [fsck]

7.5 The creation of memory swap space (swap)

7.5.1 Create swap using entity partition

1. Partition: Use gdisk to distinguish a partition on the disk for swap. Linux gdisk will set the partition ID to the Linux file system by default, so you need to set the system ID. 2. Formatting: Use the format
that creates the swap format 3. Use: Start the device with swapon 4. Observation: Pass and observemkswap

freeswapon -s

7.6 Special observations and operations of the file system

7.6.1 Waste of disk space

7.6.2 Using GNU parted for partitioning behavior (optional)

parted [设备] [指令 [参数]]
parted /dev/vda print
At least the parted command should be used

parted /dev/sda print  //先找出上一个分区的end=下一个分区的起始点  
parted /dev/sda mkpart primary fat32 36.0GB 36.5GB   
parted /dev/sda print` 

partprobe
lsblk /dev/sda7  //确定确实以及创建

mkfs -t vfat /dev/sda7 
blkid /dev/sda7
nano /etc/fstab  UUID=6032-BF38 /data/win vfat defaults 0 0  

mkdir /data/win
mount -a
df /data/win

7.7 Key Review

  • A data that can be mounted is usually called a "file system" filesystem rather than a partition!
  • Basically, the traditional file system of Linux is Ext2. The information in this file system mainly includes:
    • superblock: Record the overall information of this filesystem, including the total amount of inodes/blocks, the amount used, the remaining amount, and the format and related information of the file system;
    • inode: record the attributes of the file, a file occupies one inode, and record the block number where the data of this file is located;
    • block: actually record the content of the file, if the file is too large, it will occupy multiple blocks;
  • The data access of the Ext2 file system is an indexed file system
  • Reason for disk reorganization: block is too discrete
  • The Ext2 file system mainly includes six parts: boot sector, superblock, inode bitmap, block bitmap, inode table, data block, etc.
  • The data block places the content of the file. In Ext2, the size of the block is 1K, 2K, and 4K.
  • The inode records the attributes, permissions and other data of the file. The size of each inode is fixed, with two basic capacities of 128bytes and 256bytes. Each file only occupies one inode.
  • The journal file system (journal) will have an additional recording area to record the main activities of the file system at any time, which can speed up the system recovery time.
  • The physical link is just an additional link of the file name to the inode number;
  • Symbolic links are similar to the shortcut function of Windows
  • The use of the disk must go through: partitioning, formatting, and mounting. The commonly used commands are: gdisk, mkfs, and mount.
  • Parted check should be used when partitioning
  • Partition table format, and then judge to use fdisk/gdisk to partition, or directly use parted partition.
  • In order to consider performance, it is better to add parameters such as agcount/su/sw/extsize when formatting the XFS file system
  • You can refer to /etc/fstab to set the automatic mount at startup. After setting, be sure to use mount -a to test whether the syntax is correct or not.

8 Compression, packaging and backup of files and file systems

8.1 Purpose and technology of compressed files

8.2 Common compression instructions in Linux

8.2.1 gzip,zcat/zmore/zless/zgrep

gzip [-cdtv#] 文件名
zcat 文件名 .gz
-v compare raw data
-# compress speed and quality from 1-9 (default 6)

gzip -c services > services.gzCompress the file and keep the source file (actually output to the file services.gz via -c)

8.2.2 bzip2,bzcat/bzmore/bzless/bzgrep

bzip2 [-cdkzv#] 文件名
-c display to screen (can be saved as file)
-k keep original file

8.2.3 xz,xzcat/xzmore/xzless/xzgrep

xz [-dtlkc] 文件名
-t test file integrity

8.3 Packaging command: tar

8.3.1 tar

tar [-z|-j|-J] [cv] [-f 待创建的文件名] [filename]Pack
tar [-z|-j|-J] [tv] [-f 既有的tar文件名] [filename]View
tar [-z|-j|-J] [xv] [-f 既有的tar文件名] [filename] [-C 目录]Unzip

-c Create a packaged file, match v to view the packaged file name
-t view
-x decompress
-c -t -v cannot appear in a string of commands at the same time.


-z compress/decompress through gzip, the best file name is *.tar.gz
-j compress/decompress through bizp2, the best file name is *.tar.bz2
-J compress/decompress through xz At this time, the file name should preferably be *.tar.xz
-z -j -J, which cannot appear in the genetic command at the same time


-f is immediately followed by the file name to be processed
-C directory


The simplest tar command

  • compressiontar -j<u>c</u>v -f filename.tar.bz2
  • Inquiretar -j<u>t</u>v -f filename.tar.bz2
  • decompresstar -j<u>x</u>v -f filename.tar.bz2 -C

8.4 Backup and restore of XFS file system

8.4.1 XFS file system backup xfsdump and each level

Not only can full backup (full backup), but also cumulative backup (incremental backup).

  • xfsdump can only back up mounted filesystems.
  • xfsdump must use root authority to proceed.
  • xfsdump can only back up xfs filesystems.
  • The data under xfsdump backup can only be parsed by xfsrestore
  • xfsdump distinguishes each backup file by the UUID of the file system, so two file systems with the same UUID cannot be backed up.

xfsdump [-L S_label] [-M M_label] [-l #] [-f 备份文件] 待备份数据
xfsdump -I

8.4.2 XFS file system restore xfsresore

xfsrestore [-f 备份文件] [-L S_label] [-s] 带复原目录 <Full system recovery from a single file Restore
xfsrestore [-f 备份文件] -r 待复原目录 <the system by accumulating backup files
xfsrestore [-f 备份文件] -i 待复原目录 <Enter interactive mode

8.5 CD writing tool

mkisofs [-o 镜像文件] [-Jrv] [-V vol] [-m file] 待备份文件 ... \ > -graft-point isodir=systemdir ...

8.5.2 cdrecord CD burning tool

8.6 Other Common Compression and Backup Tools

8.6.1 dd

dd can read the content of the disk device
dd if="input_file" of="output_file" bs="block_size" count="number"
if: input file
of: output file
bs: the size of a planned blokc, the default is 512Bytes
count: how many bs

8.6.2 cpio

cpio -ovcB > [file|device] <backup
cpio -ivcdu < [file|device] <restore
cpio -ivct < [file|device] <view

9. vim program editor

9.3.2 Multi-file editing

  • The number is meaningful, 5yy is to copy 5 lines

  • The cursor moves 1G, and G moves to the beginning and end of the article respectively

  • The decimal point "." is to repeat the previous action

  • io R is often used to enter the edit mode, especially the new o and the replaced R

  • If there are aligned blocks in the article, you can use ctrl+v to copy/paste/delete

  • The environment settings can be written in ~/.vimrc

  • You can use iconv to convert the file language encoding

  • Use dos2unix and unix2dos to change each column and end-of-line break character of the file

10. bash

10.2.6 Variable keyboard reading, array and declaration: read, array, declare

read [-pt] variable

  • p can be followed by a prompt
  • t can be followed by the number of seconds to wait

declare [-aixr] variable

  • -a: Let variable become an array (array)
  • -i: Let variable become integer (intrger)
  • -x:export
  • -r: readonly, cannot unset

10.2.7 Relationship with file system and program restrictions: uklimit

ulimit [-SHacdfltu] [配额]

  • -H: hard limit, must not exceed
  • -S: Soft limit, can exceed, but will warn
  • -a: Do not follow any options and parameters, you can list all quota limits
  • -c: When an error occurs in the program, the information of the file in memory can be written into a file (core file)
  • -f: The size of the sub-oh large file that the shell can create
  • -d: The size of the largest fragmented memory (segment) that the program can use
  • -l: the amount of memory available for locking (lock)
  • -t: maximum CPU time available
  • -u: A single user can experiment with the maximum number of programs

10.2.8 Deletion, Replacement and Replacement of Variable Contents

10.3 Command aliases and historical commands

10.3.1 Command alias setting: alias, unalias

alias lm='ls -al | more'
rm='rm -i'

10.3.2 History command: history

history [n]
history [-c]
history [-raw] histfiles

10.4.5 Wildcards and special symbols

10.5 Data Flow Redirection Input: < << Output: > >> Error: 2> 2>> Overwrite, Accumulate

cat > catdile << "eof"

10.5.2

$? : command return value (correct execution returns 0)

cmd1 && cmd2: cmd1 returns 0 -> execute cmd2 (execute 2 only when 1 is executed correctly)
cmd1 || cmd2: cmd1 returns non-zero -> execute cmd2 (execute 2 only when 1 executes incorrectly)

10.6 Pipeline command (pipe)

10.6.1 Extraction commands: cut, grep

cut -d '分隔字符' -f fields <
cut -c 字符区间
Split with ":", output the 3rd and 5th strings: echo ${PATH} | cut -d ':' -f 3,5
output all characters after the 12th character:export | cut -c 12-

grep [-acinv] [--color=auto] '搜寻字串' filename
-a: Binary search data in the form of text files
-c: Count the number of times the 'search string' is found
-i: Ignore the difference in case
-n: Output line number
-v: Reverse selection, that is, there is no 'search word' string' those

10.6.2 Sorting commands: sort, wc, uniq

sort [-fbMnrtuk] [file or stdin]
-f: Ignore case
-b: Ignore the leading blank
-M: Sort by the name of the month, such as JAN, DEC
-n: Sort by pure numbers
-r: Reverse sort
-u: That is uniq
-t: separated Symbol, use [TAB] to split by default
-k: Sort by that interval Divide
the content of /etc/passwd by: and sort the third column
cat /etc/passwd | sort -t ' ' -k 3If you want to sort by numbers, add -n at the end

uniq [-ic]
-i: Ignore the difference between uppercase and lowercase characters
-c: Count
the accounts with last, only take out the account column, sort and remove the last one, and count the number of logins for each person
last | cut -d ' ' -f1 | sort | uniq -c

wc [-lwm]
-l: List only lines
-w: List only how many words
-m: How many characters How many
lines, related words, characters are there in /etc/man_db.conf
cat /etc/man_db.conf | wc

10.6.3 Two-way redirection: tee

tee [-a] file
last | tee last.list | cut -d " " -f1Save last to last.list

10.6.4 Character conversion commands: tr, col, join, paste, expand

tr [-ds] SET1 ...
-d: delete the string SET1 in the message
-s: replace repeated characters,
last | tr '[a-z]' '[A-Z]'convert the characters output by last from lowercase to uppercase,
cat /etc/passwd | tr -d ':'and delete the colon

col [-xb]
-x: convert tab key to equivalent space key

join [-ti12] file1 file2
-t: Join separates data by blank characters by default, and compares the data in the first field. If the two files are the same, they will be combined into one line, and the first field is placed first. -i: Ignore case-
1
: The first file should be analyzed with which fields
-2: The second file should be analyzed with which fields

paste [-d] file1 file2
-d: Delimiter characters can be followed, separated by TAB by default

  • : If the file part is written as -, it means data from stdin

expand [-t] file: Convert tab to a blank key
-t: Numbers can be followed, a tab can be replaced by 8 blank keys, or customized

10.6.5 Partition command: split

split [-bl] file PREFIX
-b: Later, you can borrow the size of the partitioned file, and you can connect the unit, such as b, k, m, etc. -l : partition by the
number of lines

10.6.6 Argument Substitution: xargs

xargs [-Θepn] command
-Θ: special characters such as `\ blank key, etc., this parameter can restore special characters to general characters
-e: EOF. A string can be connected later, and stop working when the string is analyzed
-p: Ask the user
-n: Number of connections

10.6.7 Use of the minus sign -

file instead, stdin, stdout

10.7 Key Review

  • env and export can observe environment variables (global variables), and export can convert custom variables into environment variables
  • set can observe all variables of the current bash
  • $? is also a variable, which is the return value after the execution of the previous command
  • loacl can observe language data
  • read allows the user to have keyboard input variables
  • ulimit limits the use of system resources by users
  • The configuration file of bash is mainly divided into login shell and non-login shell, which read etc/profile and /.bash_profile respectively, and non-login only reads /.bashrc
  • Wildcards are: *, ?, []
  • Data flow is redirected via >,2>,<
  • Continuous commands can be passed; || &&

11 regular expressions

11.2 Basic Regular Expressions

grep [-A] [-B] [--color=auto] '搜寻字串' filename
-A: add a number after it, which means that the first few lines are displayed at the same time
-B: add a number after it, which means that the next few lines are displayed at the same time

11.2.4 Basic regular expression character collection

^word: the word to be searched appears at the beginning of the line
word$: the word to be searched (word) appears at the end of the line
. : there must be an arbitrary character
\: escape character

  • : Repeat 0 to infinite characters
    [list] : A collection of characters, which lists the range you want to extract
    [n1-n2]: Same as above
    [^list]: Do not list the range
    {n,m}: continuous n to m

11.2.5 sed tool

sed [-nefr] [动作]
-n: Use silent mode, only the processed data will be listed
-e: Edit sed actions directly on the command line interface
-f: Directly write sed actions in a file, -f filename can execute filename The sed action in
-r: The sed action supports the syntax of extended regular expressions
-i: directly modify the content of the read file instead of the screen output

Action: [n1,[,n2] function]
function:
a: add nl /etc/passwd | sed '2a drink tea \hello'
c: replace nl /etc/passwd | sed '2,5c No 2-5 number'
d: delete nl /etc/passwd | sed '2,5d'
i: insert nl /etc/passwd | sed '2i drink tea'
p: print usually run together with sed -n
s: replace, you can directly replace the work, you can match regular expressionnl /etc/passwd | sed 's/要被取代的字串/新的字串/g'

11.3 Extended regular expressions

+: repeat "one or more" of the preceding RE character
? : the previous RE character of "zero or one"
|: use or to find out this string
(): find out the "group" string
() +: distinguish multiple repeated groups

11.4 Formatting of files

11.4.1 Formatted printing: printf

printf '打印格式' 实际内容
\a: Warning sound output
\b: Backspace key
\f: Clear screen form feed
\n: Output a new line
\r: Enter key
\t: Horizontal tab
\v: Vertical tab
\xNN: Convert numbers to characters
%ns: n is a number, s is a string
%ni: i is an integer
%N.nf: f stands for floating

11.4.2 awk: data processing tool

awk '条件类型1{动作1} 条件类型2{动作2} filename'
last -n 5 | awk '{print $1 "\t" $3}'List five registrants and ip, ($1 means variable 1), separated by tab

NF: the total number of fields in each line ($0)
NR: which line of data is currently being processed by awk
FS: the current separator character, the default is a blank key

Logical Operators
cat /etc/passwd | awk '{FS=":"} $3 < 10 {print $1 "\t" $3}'

The first line outputs the description (NR==1), and the operation after the second line

cat pay.txt | awk \
> 'NR==1{printf "%10s %10s %10s %10s %10s\n",$1,$2,$3,$4,"Total"}
>  NR>=2{printf "%10s %10d %10d %10d %10.2f\n",$1,$2,$3,$4,$2+$3+$4}'  

Name 1st 2nd 3rd Total
bird 200 2100 100 2400

11.4.3 File Comparison Tool

  • difff
    diff [-bBi] from-file to-file
    -b: Ignore differences in whitespace in a line
    -B: Ignore differences in blank lines
    -i: Ignore differences in case

  • cmp
    cmp [-l] file1 file2
    -l: List all the differences (cmp only lists the first one by default)

  • patch
    patch -pN < patch_fileupdate
    patch -R -pN < patch_filerestore
    -p: cancel several layers of directories
    diff -Naur passwd.old passwd.new > passwd.patch

12.3 Make good use of judgment

12.3.1 Using the test function of the test command

test -e /tmp && echo "exist" || echo "Not exist" Check if /tmp exists

  • 1. Prompt whether the file exists:
    -e: Whether the file name exists
    -f: Whether the file name exists, and
    it is a file -d: Whether the file name exists, and it is a directory
    -b: Whether it exists, and it is a block device device
    -c: whether it exists, and it is a character device device
    -S: whether it exists, and it is a Socket file
    -p: whether it exists, and it is a FIFO (pipe) file
    -L: whether it exists, and it is a link file

  • 2. File permission detection prompt:
    -r: readable
    -w: writable
    -x: detect whether the file name exists and has "executable" permission?
    -u: Detect whether the file name exists and has the attribute "SUID"?
    -g: detect if the filename exists and has the attribute "SGID"?
    -k: Detect if the filename exists and has the attribute "Sticky bit"?
    -s: detect whether the file name exists and is a "non-blank file"?

  • 3. Comparison of two files
    -nt: (newer than) to determine whether file1 is newer than file2
    -ot: (older than) to determine whether file1 is older than file2
    -ef: to determine whether file1 and file2 are the same file, which can be used to determine the hard link on the judgment. The main significance is to determine whether the two files point to the same inode.

  • 4. Regarding the judgment between two integers
    such as test n1 -eq n2
    -eq: two values ​​are equal (equal)
    -ne: two values ​​are not equal (not equal)
    -gt: n1 is greater than n2 (greater than)
    -lt: n1 Less than n2 (less than)
    -ge: n1 is greater than or equal to n2 (greater than or equal)
    -le: n1 is less than or equal to n2 (less than or equal)

  • 5. Data
    test -z string for judging the string: Is the judging string 0? If string is an empty string, it is true
    test -n string: Determine if the string is not 0? false if string is an empty string. -n can also be omitted
    test str1 == str2: determine whether str1 is equal to str2, if equal, return true
    test str1 != str2: determine whether str1 is not equal to str2, if equal, return false

  • 6. Multiple condition determination, for example: test -r filename -a -x filename
    -a: (and) two conditions are established at the same time! For example, test -r file -a -x file, only returns true when the file has both r and x permissions.
    -o: (or) Either of the two conditions is established! For example, test -r file -o -x file, when the file has r or x permission, it can return true.
    !: Reverse state, such as test! -x file, when file does not have x, return true

12.3.2 Judgment symbol [ ]

"$HOME" == "$MAIL"To judge whether HOME and MAIL are equal, a space is required

12.3.3 Shell script default variables ($0, $1...)

/path/t0/scriptname		opt1	opt2	opt3	opt4  
		$0				 $1		 $2		 $3 	 $4

$#: represents the number of subsequent parameters
$@: represents all opts of $1$2$3$4, each variable is independent, enclosed in double quotes
$*: represents $1 $2 $3 $4

  • sh
  • t: Causes the parameter variable number to be shifted
    and can be followed by numbers

12.4 Conditional judgment formula

12.4.1 Usage if…then

if [条件1]; then   
	执行的指令  
elif [条件2]; then
	执行的命令
else
fi

date -d,–date=STRING Display the time specified by STRING
Calculate the time of retirement and calculate the birthday

12.4.2 Use case...esac to judge

case ${1} in
	"case1")
		echo "asd"
		;;
	"case2")
		echo "222"
		;;
	*)
		echo "others"
		;;
esac

12.4.3 function function

funciton printiit(){
	echo -n "your choice is ${1}"
}

**printit 1**;

12.5 loop cycle

12.5.1 while do done, until do done

12.5.2 for(…in…)do…done

12.5.3 for(…;…;…)do…done

12.6 Tracing and debugging of shell script

sh [-nvx] script.sh
-n: Do not execute scipt, only perform syntax check
-v: Output the content of the script before executing scipt
-x: Display the content of the moral scipt to the screen

12.7 Review review

  • If the execution of the script is executed by source, it means that it is executed in the parent program bash
  • If you need to make judgments, you can use test or square brackets ([ ]) to process
  • $0,$1, 2... 2... 2... @ all have special meanings

13 Linux account management and ACL permission setting

13.1 Linux accounts and groups

13.1.1 User ID: UID GID

13.2 Account Management

13.2.2 Add and remove useradd, configuration file passwd, usermod, userdel

useradd [-u UID] [-g 初始群组] [-G 次要群组] [-mM] [-c 说明栏] [-d 主文件夹绝对路径] [-s shell] 使用者账号名

-u: followed by UID, which is a set of numbers. Directly assign a specific UID to this account;
-g: The group name followed is the initial group we mentioned above~ The GID of this group will be placed in the fourth field of /etc/passwd.
-G : The following group name is the group that this account can also join. This option and parameter will modify the relevant data in /etc/group!
-M : Mandatory! Do not create user home folders! (system account default value)
-m : Mandatory! To create a user home folder! (General account default value)
-c: This is the description content of the fifth column of /etc/passwd ~ we can set it as we like ~ -d
: Specify a certain directory to be the main folder instead of using the default value. Be sure to use absolute paths!
-r: create a system account, the UID of this account will be limited (refer to /etc/login.defs)
-s: followed by a shell, if not specified, the default is /bin/bash~ -e
: followed Then a date, the format is "YYYY-MM-DD". This item can be written into the eighth field of shadow,
which is the setting item of the account expiration date;
-f: followed by the item in the seventh field of shadow, specifying whether the password will expire . 0 is invalid immediately,
-1 is never invalid (the password will only expire and be forced to reset when logging in.)

passwd [--stdin] [帐号名称] &lt;==所有人均可使用来改自己的密码  
passwd [-l] [-u] [--stdin] [-S] [-n 日数] [-x 日数] [-w 日数] [-i 日期] 帐号   

Options and parameters:
–stdin : Can pass data from the previous pipeline as password input, helpful for shell scripts!
-l: It means Lock, it will add ! to the front of the second column of /etc/shadow to make the password invalid;
-u: Opposite to -l, it means Unlock!
-S : List password-related parameters, that is, most of the information in the shadow file.
-n: followed by the number of days, the fourth field of shadow, how long the password cannot be changed.
-x: followed by the number of days, the fifth field of shadow, how long the password must be changed
-w: followed by the number of days, the sixth field of shadow , the number of warning days before the password expires
-i: followed by "date", the seventh field of shadow, the password expiration date

chage [-ldEImMW] 帐号名
Options and parameters:
-l: list the detailed password parameters of the account;
-d: follow the date, modify the third field of shadow (the date of the last password change), format YYYY-MM-DD
-E: follow the date, Modify the eighth field of shadow (account expiration date), format YYYY-MM-DD
-I: followed by the number of days, modify the seventh field of shadow (password expiration date)
-m: followed by the number of days, modify the fourth field of shadow (the password is the shortest reserved Days)
-M : Followed by the number of days, modify the fifth field of the shadow (how long does the password need to be changed)
-W : Followed by the number of days, modify the sixth field of the shadow (the date of warning before the password expires)

usermod [-cdegGlsuLU] username
Options and parameters:
-c: Followed by the description of the account, that is, the description column of the fifth column of /etc/passwd, you can add some descriptions of the account.
-d: followed by the main folder of the account, that is, to modify the sixth column of /etc/passwd;
-e: followed by the date, the format is YYYY-MM-DD, which is the eighth field data in /etc/shadow La!
-f : followed by the number of days, which is the seventh field of shadow.
-g : Followed by the initial group, modify the fourth field of /etc/passwd, which is the field of GID!
-G: Followed by the secondary group, modify the group that the user can support, the modification is /etc/group~
-a: Used with -G, it can "increase the support of the secondary group" instead of " Set "Oh!
-l : followed by the account name. That is to modify the account name, the first column of /etc/passwd!
-s : followed by the actual file of the shell, such as /bin/bash or /bin/csh, etc.
-u : followed by the UID number! That is, the data in the third column of /etc/passwd;
-L: Temporarily freeze the user's password so that he cannot log in. In fact, only the password column of /etc/shadow is changed.
-U: Remove the ! in the /etc/shadow password column, and thaw it!

userdel [-r] username
Options and parameters:
-r : Delete together with the user's home folder

13.2.2 User functions

  • id id username
  • finger finger [-s] username
  • chfn chfn [-foph] username (change finger)
  • chsh chsh [-ls] (change shell

13.2.3 Adding and removing groups

  • groupadd [-g gid] [-r] 群组名称
    Options and parameters:
    -g: Followed by a specific GID, used to directly give a GID ~
    -r: Create a system group! Related to GID_MIN in /etc/login.defs.

  • groupmod [-g gid] [-n group_name] 群组名
    Options and parameters:
    -g: modify the existing GID number;
    -n: modify the existing group name

  • groupdel [groupname]

  • gpasswd groupname
    gpasswd [-A user1,...] [-M user3,...] groupname
    gpasswd [-rR] groupname
    Options and parameters:
    : If there is no parameter, it means to give groupname a password (/etc/gshadow)
    -A : Hand over the control of groupname to the subsequent user management (the administrator of the group)
    -M : Set Some accounts join this group!
    -r: Remove the password of groupname
    -R: Disable the password field of groupname
    gpasswd [-ad] user groupname
    Options and parameters:
    -a: Add a user to the group groupname!
    -d : Remove a user from the group groupname.

14 Disk quota (Quota) and advanced file management system

15 Routine job scheduling (crontab)

16 A Preliminary Study on Program Management and SELinux

17 Understanding System Services Linux

Guess you like

Origin blog.csdn.net/cbx0916/article/details/130514984