Alibaba cloud server basic Linux instruction experiment (1-5)

Concise programming 2022-06-24 08:04:55 阅读数:373

alibabacloudserverbasiclinux

Alibaba cloud server basic experiment - text processing

Alibaba cloud server basic experiment - text processing

Address

https://developer.aliyun.com/adc/expo/linux
 Insert picture description here

Experimental setup

 Insert picture description here
After the resource is created , Click the right side. Web Terminal Connect ECS The server .
 Insert picture description here

Text editing tools Vim

vim Three modes of operation

vim There are three modes of operation , Command mode (Command mode)、 The input mode (Insert mode) And bottom line command mode (Last line mode).

Command mode

Control cursor movement and enter commands in command mode , The text can be copied 、 Paste 、 Delete and search etc .

Use command vim filename Then enter the editor view , The default mode is command mode , At this time, tapping the keyboard letter will be recognized as a command , For example, tap twice continuously on the keyboard d, The line where the cursor is located will be deleted .

The following are shortcuts commonly used in command mode :
 Insert picture description here
 Insert picture description here
 Insert picture description here

 Insert picture description here

The input mode

Press... In command mode i or a Key to enter the input mode , In input mode , You can normally use keyboard keys to insert and delete text .

last line node

Press... In command mode : Key to enter the bottom line command mode , In the bottom line command mode, you can enter a single or multiple character command .

Press down ECS Key back to command mode , And enter the baseline command :ce, Center the title of the poem .
 Insert picture description here

Text file view command

cat

Command description :cat The command is used to view plain text files with less content .

Command format :cat [ Options ] [ file ].

Command parameter description :

Parameters explain
-n or –number According to the line Numbers
-b or –number-nonblank According to the line Numbers , But do not number blank lines
-s or –squeeze-blank When the above encounter with a continuous two lines of blank lines , Show only one blank line

 Insert picture description here

Command usage example :

Write a self increasing sequence to test.txt In file .
for i in $(seq 1 10); do echo $i >> test.txt ; done

 Insert picture description here

Empty the contents of the file .
cat /dev/null > test.txt

 Insert picture description here

more

Command description :more The command displays the contents of the file from front to back .

Common operation command :

operation effect
Enter Down n That's ok ,n Need to define , The default is 1 That's ok
Ctrl+F Or the space bar (Space) Scroll down one page
Ctrl+B Scroll up one page
= Output the line number of the current line
! command call Shell Carry out orders
q sign out more

Command usage example :

From 20 Line start paging to view the system log file /var/log/messages.
more +20 /var/log/messages

 Insert picture description here

less

Command description :less The command can display files or other output in pages , And moe Command similar , But use less You can browse files at will , and more Move forward only , But can't move back .

Command format :less [ Parameters ] file .

Command parameter description :

Parameters explain
-e When the file display is finished , Leave automatically
-m The display is similar to more Percentage of orders
-N Show the line number of each line
-s Show a row of consecutive empty actions

Command common operations :

Shortcut key explain
/ character string Search down the string
? character string Search up the string
n Repeat the previous search
N Repeat the previous search in reverse
b or pageup key Page up
Space bar or pagedown key Turn down a page
u Turn half a page forward
d Turn back half a page
y Roll a line forward
Enter key Scroll back one line
q sign out less command

Command usage example :

Check the command history and pass less Pagination display .
history | less

 Insert picture description here

head

Command description :head The command is used to view the contents of the specified number of lines at the beginning of the file .

Command format :head [ Parameters ] [ file ].

Command parameter description :

Parameters explain
-n [ Row number ] Displays the contents of the file starting with the specified line , The default is 10
-c [ Number of characters ] Displays the number of characters starting with the specified number
-q Do not display file name information , Applicable to multiple files , When there are multiple files, the file name will be displayed by default

Command usage example :

see /etc/passwd Before the document 5 Row content .
head -5 /etc/passwd

 Insert picture description here

tail

Command description :tail The command is used to view the back of a document N Line or continue to refresh content .

Command format :tail [ Parameters ] [ file ].

Command parameter description :

Parameters explain
-f Show the latest additions to the file
-q When there are multiple file parameters , Do not output individual file names
-v When there are multiple file parameters , Always output individual file names
-c [ Number of bytes ] Show the end of the file n Byte content
-n [ Row number ] Show the end of the file n Row content

Command usage example :

see /var/log/messages The latest version of the system log file 10 That's ok , And keep refreshing in real time .
tail -f -n 10 /var/log/messages

 Insert picture description here
Press ctrl+c Key to exit the real-time text viewing interface .

stat

Command description : Used to display the details of the file , Include inode、atime、mtime、ctime etc. .

Command usage example :

see /etc/passwd File details .
stat /etc/passwd

 Insert picture description here

wc

Command description :wc Command is used to count the number of lines of the specified text 、 Number of words 、 Number of bytes .

Command format :wc [ Parameters ] [ file ].

Command parameter description :

Parameters explain
-l Show only rows
-w Show only the number of words
-c Show only the number of bytes

Command usage example :

Statistics /etc/passwd The number of lines in the file .
wc -l /etc/passwd

 Insert picture description here

file

Command description : file The command is used to identify the file type .

Command format :file [ Parameters ] [ file ].

Command parameter description :

Parameters explain
-b When listing the identification results , Do not show file name
-c Detailed display of instruction execution process , A situation that facilitates troubleshooting or analysis of program execution
-f [ file ] Specify name file , When its content has one or more file names , Give Way file Identify these documents in order , The format is one file name per column
-L Directly show the file category that the symbolic connection points to

Command usage example :

see /var/log/messages The file type of the file .
file /var/log/messages

 Insert picture description here

diff

Command description :diff Command is used to compare the differences between files .

Command usage example :

Construct two similar files
echo -e ' first line \n The second line \n I am a log1 The first 3 That's ok \n In the fourth row \n The fifth row \n Sixth elements ' > 1.log
echo -e ' first line \n The second line \n I am a log2 The first 3 That's ok \n In the fourth row ' > 2.log

 Insert picture description here

Use diff Look at the difference between the two files

 Insert picture description here
Compare... In the results 3c3 Indicates that two files are in the 3 Different lines ,5,6d4 Express 2.log Compared to the file 1.log The document is on page 4 There are fewer rows 1.log File first 5 And the 6 That's ok

Text file processing command

grep

Command description :grep The command is used to find the strings in the file that match the conditions .

grep The full name is Global Regular Expression Print, Represents the global regular expression version , It can search for text using regular expressions , And print out the matching lines .

stay Shell Script ,grep Indicates the status of the search by returning a status value :

0: The match is successful .
1: Matching failure .
2: The file searched does not exist .

Command format :grep [ Parameters ] [ Regular expressions ] [ file ].

Command common parameter description :

Parameters explain
-c or –count Calculated in line with the number of columns styles
-d recurse or -r Specify that you want to find a directory instead of a file
-e [ Template Styles ] Specifies a string as a style for finding the contents of a file
-E or --extended-regexp Use... As an extended regular expression
-F or --fixed-regexp The style seen as a list of fixed strings
-G or --basic-regexp It will be treated as ordinary style of notation to use
-i or --ignore-case Ignore character case differences
-n or --line-number Before displaying the line in line with the style of , Mark the number of columns in the row number
-v or --revert-match Display does not contain matching text of all lines

Command usage example :

see sshd The line number of the listening port configuration in the service configuration file .
grep -n Port /etc/ssh/ssh_config

 Insert picture description here

The number of columns in the text of the query string .
grep -c localhost /etc/hosts

 Insert picture description here

Reverse lookup , Do not display qualified lines .
ps -ef | grep sshd
ps -ef | grep -v grep | grep sshd

 Insert picture description here

Recursively find files containing keywords in the directory .
grep -r *.sh /etc

 Insert picture description here

Use regular expressions to match httpd Relevant configuration of abnormal status code response in configuration file .
grep 'ntp[0-9].aliyun.com' /etc/ntp.conf

 Insert picture description here

sed

Command description :sed Is a flow editor , It's a very medium tool in text processing , Perfect for regular expressions .

  1. When dealing with , Store the currently processed rows in a temporary buffer , It's called pattern space (pattern space).
  2. Then use sed Command processing buffer contents , After processing , Send the contents of the buffer to the screen .
  3. Next line , This is repeated , Until the end of the file .

Be careful :

sed The command does not modify the original file , For example, the delete command only means that some lines do not print out , Instead of deleting it from the original document .
If you want to change the source file , Need to use -i Options .

Command format :sed [ Parameters ] [ action ] [ file ].

Parameter description :

Parameters explain
-e [script] Execute multiple script
-f [script file ] Execute assignment script file
-n Show only script The result of the treatment
-i Output to original file , Silent execution ( Modify the original document )

Action description :

action explain
a Add content after the line
c Replacement row
d Delete row
i Insert... Before the line
p Print related lines
s replace content

Command usage example :

Delete the first 3 Line to the last line .
sed '3,$d' /etc/passwd

 Insert picture description here

Add a new line on the last line .
sed '$a admin:x:1000:1000:admin:/home/admin:/bin/bash' /etc/passwd

 Insert picture description here

replace content
sed 's/SELINUX=disabled/SELINUX=enforcing/' /etc/selinux/config

 Insert picture description here

Replacement row
sed '1c abcdefg' /etc/passwd

 Insert picture description here

awk

Command description : and sed Command similar ,awk The command also scans the file line by line ( From 1 Line to last line ), Find the line that contains the target text , If the match is successful , Then the user's desired action will be performed on that line ; conversely , Do nothing with the line .

Command format :awk [ Parameters ] [ Script ] [ file ].

Parameter description :

Parameters explain
-F fs Specified in fs As a separator for the input line ,awk The default separator for the command is a space or tab
-f file Read awk Script
-v val=val Before executing the process , Set a variable var, And set the initial value to val

Built-in variables :

Variable purpose
FS Field separator
$n Specify the number of divisions n A field , Such as $1、$3 Separate indication control 1、 The third column
$0 The entire line of text currently read
NF Record the number of fields in the current processing line ( Number of columns )
NR Record the number of rows currently read in
FNR The line number of the current line in the source file

awk You can also specify the running time of script commands . By default ,awk A line of text will be read from the input , Then execute the program script... For the data of that row , But sometimes you may need to run some script commands before processing data , That's what you need to use BEGIN keyword ,BEGIN Will be in awsk Before reading data, the script command specified after the keyword is enforced .

and BEGIN Keywords correspond to ,END Keyword allows us to specify some script commands ,awk They will be executed after reading the data .

Command usage example :

View this machine IP Address .
ifconfig eth0 |awk '/inet/{
print $2}'

 Insert picture description here

Check the remaining disk capacity of this machine .
df -h |awk '/\/$/{
print $4}'

 Insert picture description here

Count the number of system users .
awk -F: '$3<1000{
x++} END{
print x}' /etc/passwd

 Insert picture description here

Output where login Shell Don't to nologin ending ( Right. 7 Fields to do !~ Reverse matching ) Username 、 Sign in Shell Information .
awk -F: '$7!~/nologin$/{
print $1,$7}' /etc/passwd

 Insert picture description here

Output /etc/passwd The first three lines of the file record the user name and user uid.
head -3 /etc/passwd | awk 'BEGIN{
FS=":";print "name\tuid"}{
print $1,"\t"$3}END{
print "sum lines "NR}'

 Insert picture description here

see tcp The number of connections .
netstat -na | awk '/^tcp/ {
++S[$NF]} END {
for(a in S) print a, S[a]}'

 Insert picture description here

Close all processes of the specified service .
ps -ef | grep httpd | awk {
'print $2'} | xargs kill -9

cut

Command description :cut The command is mainly used to cut strings , You can cut the input data and then output .

Command format :cut [ Parameters ] [ file ].

Parameter description :

Parameters explain
-b Split in bytes
-c Split in characters
-d Custom delimiter , The default is tab

Command usage example :

Cut by byte .
echo "hello world"|cut -b 1-3
echo "hello world"|cut -b 1,3

 Insert picture description here
 Insert picture description here

Cut by character .
echo "hello world" | cut -c 1-3
echo "hello world" | cut -c 1,3

 Insert picture description here

Cut according to the specified characters .
echo "hello,world,ok"|cut -d , -f 1,3

 Insert picture description here

tr

Command description :tr The command is used to replace characters from standard input 、 Compress and delete .

Command format :tr [ Parameters ] [ Text ].

Parameter description :

Parameters explain
-c Invert the specified character
-d Delete specified characters
-s Reduce repeated characters to one character
-t [ First character set ] [ Second character set ] Delete more characters in the first character set than in the second character set , Make two character sets equal in length

Command usage example :

Convert input characters from uppercase to lowercase .
echo "HELLO WORLD" | tr 'A-Z' 'a-z'

 Insert picture description here

Delete character
echo "hello 123 world 456" | tr -d '0-9'
Compress characters .
echo "thissss is a text linnnnnnne." | tr -s ' sn'

 Insert picture description here

Generate random passwords
cat /dev/urandom | tr -dc a-zA-Z0-9 | head -c 13

 Insert picture description here

 Insert picture description here

Alibaba cloud server basic experiment II system management

echo

Command description :echo The command is used to output the value after string or variable extraction at the terminal .

Command format :echo [ character string | $ Variable ]

Examples of command usage :

 Show normal string
Show variable

First, in the shell Define a temporary variable in the environment name.

export name="Tom"

Use echo The command will change the variable name The value of is displayed to the terminal .

echo $name

 Insert picture description here

Show results directed to file

The following command will change the text This is a test text. Redirect output to file test.txt in , If the file already exists , The contents of the file will be overwritten , Create... If it doesn't exist . among > The output symbol indicates redirection .

echo "This is a test text." > test.txt

 Insert picture description here

If you want to append text to the end of the file , Instead of covering it , Please use >> Output additional redirection symbol .

Show command execution results

The following command will display the current working path on the terminal .

echo `pwd`

Use $(command) Form can achieve the same effect .

echo $(pwd)

 Insert picture description here

date

Command description :date The command is used to display and set the time and date of the system .

Command format :date [ Options ] [+ Format ]

among , Some control characters of time format are explained as follows :

character explain
%a Abbreviation of week name in local time ( for example : Japan , On behalf of Sunday )
%A The full name of the week in local time ( for example : Sunday )
%b Abbreviation of month name in local time ( for example : One , For January )
%B The full name of the month in local time ( for example : January )
%c Date and time of local time ( for example :2005 year 3 month 3 Japan Thursday 23:05:25)
%C century ; such as %Y, Usually omit the last two digits of the current year ( for example :20)
%d Monthly dates ( for example :01)
%D Monthly dates ; be equal to %m/%d/%y
%F Full date format , Equivalent to %Y-%m-%d
%j Date by year (001-366)
%p Date by year (001-366)
%r Local time 12 Hour clock time ( for example :11:11:04 Afternoon )
%R24 The hours and minutes of the hour , Equivalent to %H:%M
%s since UTC Time 1970-01-01 00:00:00 The number of seconds that have passed since
%T Time , be equal to %H:%M:%S
%U Weeks of the year , Take Sunday as the first day of every week (00-53)
%x Date description in local time ( for example :12/31/99)
%X Time description in local time ( for example :23:13:48)
%w What day of the week (0-6),0 On behalf of the Monday
%W Weeks of the year , Take Monday as the first day of every week (00-53)

Examples of command usage :

View the current system time in the default format

date

 Insert picture description here

View the current system time in the specified format

date "+%Y-%m-%d %H:%M:%S"

 Insert picture description here

Check out today is the day of the year

date "+%j"

 Insert picture description here

Set the current time of the system to 2020 year 02 month 20 Japan 20 spot 20 branch 20 second

date -s "20200220 20:20:20"

 Insert picture description here

Correct system time , Synchronize with network time

install ntp Timing tool
yum -y install ntp

 Insert picture description here

use ntpdate Update time from time server
ntpdate time.nist.gov

 Insert picture description here

wget

Command description : Download files from the terminal .

Command format :wget [ Parameters ] Download address

Parameter description :

Parameters effect
-b Background download
-P Download to the specified directory
-t max retries
-c Breakpoint continuation
-p Download all resources on the page , Including pictures 、 Video etc.
-r Recursive download

example

Download a picture to the path /root/static/img/ in ,-p The default value of the parameter is the current path , If the specified path does not exist, it will be created automatically .

wget -P /root/static/img/ https://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=%E5%9B%BE%E7%89%87&step_word=&hs=0&pn=34&spn=0&di=7108135681917976577&pi=0&rn=1&tn=baiduimagedetail&is=0%2C0&istype=0&ie=utf-8&oe=utf-8&in=&cl=2&lm=-1&st=undefined&cs=3425731243%2C1645767863&os=2542384575%2C721583306&simid=3420648579%2C408723673&adpicid=0&lpn=0&ln=1533&fr=&fmq=1655861908890_R&fm=&ic=undefined&s=undefined&hd=undefined&latest=undefined&copyright=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&ist=&jit=&cg=&bdtype=0&oriquery=&objurl=https%3A%2F%2Fgimg2.baidu.com%2Fimage_search%2Fsrc%3Dhttp%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2Ftp02%2F1Z9191923035R0-0-lp.jpg%26refer%3Dhttp%3A%2F%2Fimg.jj20.com%26app%3D2002%26size%3Df9999%2C10000%26q%3Da80%26n%3D0%26g%3D0n%26fmt%3Dauto%3Fsec%3D1658453915%26t%3D1b59a261787e116ed715e0c0d262eabc&fromurl=ippr_z2C%24qAzdH3FAzdH3Fooo_z%26e3B33da_z%26e3Bv54AzdH3FprAzdH3F8dbc00_z%26e3Bip4s&gsm=1e&rpstart=0&rpnum=0&islist=&querylist=&nojc=undefined&dyTabStr=MCwzLDYsMSw0LDIsNSw3LDgsOQ%3D%3D

 Insert picture description here

 Insert picture description here

 Insert picture description here

cd /root/static/img
ls

 Insert picture description here
 Insert picture description here

ps

Command description :ps The command is used to view the process status in the system .

Command format :ps [ Parameters ].

Command parameter description :

Parameters effect
-a Display all programs under the current terminal , Including other users' programs
-u Display program status in a user oriented format
-x Display the process without control terminal , Display the specific path of each command at the same time
-e When listing programs , Shows the environment variables used by each program
-f Show all current processes
-t Specify terminal number , And list the status of the program belonging to the terminal

Command usage example :

ps -ef | grep sshd

 Insert picture description here

top

Command description :top The command dynamically monitors information such as process activity and system load .

Command usage example :

top

 Insert picture description here
Command output parameter interpretation :

The above command output view is divided into two areas , A statistical information area , A process information area .

 Statistics area
The first line of information is : system time 、 The elapsed time 、 Number of login terminals 、 System load ( The three values are 1 minute 、5 minute 、15 Average in minutes , A smaller value means a lower load ).
The second line of information is : Total processes 、 Number of running processes 、 The number of processes in sleep 、 Number of processes stopped 、 The number of dead processes .
The third line of information is : Percentage of resources occupied by users 、 The percentage of resources occupied by the system kernel 、 Percentage of process resources that have changed priority 、 Percentage of free resources, etc .
The fourth line of information is : Total physical memory 、 Memory usage 、 Amount of free memory 、 The amount of memory used as kernel cache .
The fifth line of information is : Total virtual memory 、 Virtual memory usage 、 Virtual memory free 、 Amount of preloaded memory .
Process information area
Name meaning
PID process ID
USER User name of the process owner
PR Process priority
NInice value . Negative value indicates high priority , A positive value indicates a low priority
VIRT Total virtual memory used by the process , Company kb
RES Used by process 、 Physical memory size not swapped out , Company kb
SHR Shared memory size , Company kb
S Process status D: Uninterrupted sleep R: Running S: sleep T: stop it Z: Zombie process
%CPU Last updated to now CPU Percentage of time used
%MEM Percentage of physical memory used by the process
TIME+ Used by process CPU Total time , Company 1/100 second
COMMAND Command name

Press q Press the key to exit the monitoring page .

pidof

Command description :pidof The command is used to query the of the specified service process PID value .

Command format :pidof [ The service name ].

Command parameter description :

Parameters explain
-s Return only one process number
-c Only show running on root Process under Directory , This option is only for root User valid
-o Ignore the process with the specified process number
-x Show the process started by the script

Command usage example :

Query out crond All processes under the service ID.

pidof crond

 Insert picture description here

kill

Command description :kill The command terminates the specified PID The service process of .

kill The specified information can be sent to the program . The default message is SIGTERM(15), The specified procedure may be terminated . If the program still cannot be terminated , You can use SIGKILL(9) Message attempt to force deletion of program .

Command format :kill [ Parameters ] [ process PID].

Command usage example :

Delete pid by 1247 The process of .

kill -9 1247

 Insert picture description here

killall

Command description :killall Command is used to terminate all processes corresponding to the service with the specified name .

Command format :killall [ Process name ].

Command usage example :

Delete crond All processes under the service .

killall crond

 Insert picture description here
 Insert picture description here
 Insert picture description here

System status detection command

ifconfig

Command description :ifconfig The command is used to obtain information such as network card configuration and network status .

Command usage example :

Get information about network card configuration and network status .
ifconfig

 Insert picture description here
Command output description :

 The first line of the first part displays the status information of the network card .
eth0 Indicates the first network card .
UP On behalf of network card .
RUNNING The network cable representing the network card is connected .
MULTICAST Indicates support for multicast .
The second line shows the network information of the network card .
inet(IP Address ):172.16.132.195.
broadcast( Broadcast address ):172.16.143.255.
netmask( Mask address ):255.255.240.0.
RX Indicates the condition of receiving a packet ,TX Indicates the sending of packets .
lo Indicates the loopback network card of the host , Is a special network interface , Not connected to any actual equipment , But completely implemented by software . And loopback address (127.0.0.0/8 or ::1/128) Different , The loopback network card is displayed as a piece of hardware to the system . Any data sent to the network card will be immediately received by the same network card .

uname

Command description :uname Commands are used to view information such as system kernel and system version .

Command syntax :uname [-amnrsv][–help][–version]

Command usage example :

Display system information .
uname -a

 Insert picture description here

Displays the hardware architecture of the current system .
uname -i

 Insert picture description here

Displays the operating system release number .
uname -r

 Insert picture description here

Show operating system name .
uname -s

 Insert picture description here

Show host name .
uname -n

 Insert picture description here

uptime

Command description :uptime Used to view the load information of the system .

Command usage example :

Check the load information of the system .
uptime

 Insert picture description here

free

Command description :free Used to display the memory usage information in the current system .

Command syntax :free [-bkmotV][-s < Seconds apart >]

Command parameter description :

Parameters explain
-b With Byte Display memory usage in units
-k With KB Display memory usage in units
-m With MB Display memory usage in units
-h Display memory usage in appropriate units , The maximum is three digits , Automatically calculate the corresponding unit value .

Command usage example :

Display the memory usage information in the current system .
free -h

 Insert picture description here
Command output description :

Parameters explain
total Total physical memory
used The amount of memory used
free Amount of memory in space
share Total memory shared by multiple processes
buff/cache Number of memory used by the application
available Amount of memory available
Swap Virtual memory ( Alibaba cloud ECS The server does not enable virtual memory by default )

who

Command description :who The command displays information about all users currently on the local system .

Command usage example :

Show users currently logged in to the system

who

 Insert picture description here

Show user login source

who -l -H

 Insert picture description here

Show current user only

who -m -H

 Insert picture description here

Reduced mode display

who -q

 Insert picture description here

last

Command description : last The command is used to display the user's recent login information .

Command usage example :

Display the user's latest login information .
 last

 Insert picture description here
Because these information are saved in the system in the form of log files , Hackers can easily tamper with content , Therefore, the information output by this command cannot be used as the basis for whether the server is invaded .

history

Command description :history Commands are used to display commands that have been executed in history .

bash Default record 1000 A historical command executed , Recorded in ~/.bash_history In file .

Command usage example :

Show the latest 10 A command that has been executed .
history 10

 Insert picture description here

Clear history .
history -c

 Insert picture description here
 Insert picture description here

Alibaba cloud server basic experiment 3 disk management commands

df command

df Command description : This command checks the disk space usage of the file system . You can use this command to get the space occupied by the hard disk , How much space and other information is left .

df Command syntax :df [ Parameters ] [ Directory or filename ]

Parameter description :

Parameters explain
-a List all file systems , Including system specific /proc Equal file system .
-k With KBytes In units of , Returns the capacity of each file system .
-m With MBytes In units of , Returns the capacity of each file system .
-h With GBytes、MBytes、KBytes In units of , Returns the capacity of each file system .
-H With M=1000K replace M=1024K The carry mode of displays the capacity of each file system .
-T Show file system type .
-i Show inode Information .

Command usage example :

Display disk usage .

Execute the following command , Display disk usage .

df

 Insert picture description here

With inode Mode to display disk usage .

Execute the following command , With inode Mode to display disk usage .

df -i

 Insert picture description here

Display all special file formats in the system 、 Name and disk usage .

Execute the following command , Display all special file formats in the system 、 Name and disk usage .

df -aT

 Insert picture description here

With GBytes、MBytes、KBytes Display the capacity of each file system in equal format .

Execute the following command , With GBytes、MBytes、KBytes Display the capacity of each file system in equal format .

df -h

 Insert picture description here

du command

du Command description : View disk space used .du And df The difference between commands is ,du The command is used to view the space used by file and directory disks .

du Command syntax :du [ Parameters ] [ File or directory name ]

Parameter description :

Parameters explain
-a List all file and directory capacities .
-h With G、M、K In units of , Return capacity .
-s List the total amount .
-S List the total amount excluding subdirectories .
-k With KBytes In units of , Return capacity .
-m With MBytes In units of , Return capacity .

Command usage example :

List the capacity of all folders in the current directory .

Execute the following command , List the capacity of all folders in the current directory .

du

 Insert picture description here

List the capacity of all folders and files in the current directory .

Execute the following command , List the capacity of all folders and files in the current directory .

du -a

 Insert picture description here

List the capacity of all folders and files in the current directory , And G、M、K Format display capacity .

Execute the following command , List the capacity of all folders and files in the current directory .

du -ah

 Insert picture description here

List the capacity occupied by each directory under the root directory , And MBytes The unit shows the capacity .

Execute the following command , List the capacity occupied by each directory under the root directory , And MBytes The unit shows the capacity .

du -sm /* 

 Insert picture description here

fdisk command .

fdisk Command description : This command is used for disk partitioning .

fdisk Command syntax :fdisk [-l] Device name

Parameter description :

Parameters explain
-l Output all partition contents of the following device name . If only fdisk -l when , Then the system will list the partition of the devices that can be found in the whole system .

fdisk Command usage example :

List the partition information of all devices in the system .

Execute the following command , List the partition information of all devices in the system .

fdisk -l

 Insert picture description here

List the disks where the root directory is located in the system , And check the relevant information in the hard disk .

Execute the following command , Find the disk name where the root directory is located .

df /

 Insert picture description here

Execute the following command , Diskette /dev/vda Partition operation .

fdisk /dev/vda

 Insert picture description here

Be careful :

When partitioning a disk , The disk name does not contain numbers .

Input m get help

 Insert picture description here
Execute the following command , Check disk status .

p

 Insert picture description here
Execute the following command , Do not store any operations and leave .

q

 Insert picture description here

 Insert picture description here

Alibaba cloud server basic experiment 4 file directory management commands

ls

Command description : ls The command is used to display the contents of the specified working directory .

Command format :ls [ Parameters ] [ Directory name ].

Parameter description :

Parameters explain
-a Show hidden files and directories ( Including hidden files )
-l Change the permissions of the file 、 The owner 、 File size and other details are listed (ll Equate to ls -l)
-r List the files in reverse order ( By default, it is in English positive order )
-t List the files in positive order of creation time
-R Recursively traverse the files in the directory

Command usage example :

View all files in the current directory ( Including hidden files ).

ll -a

 Insert picture description here

pwd

Command description : Get the absolute path of the current working directory

pwd

 Insert picture description here

cd

Command description :cd The command is used to switch working directories .

cd /usr/bin

In path representation :

 A half full stop (.) Represents the current directory , For example, path ./app/log Equate to app/log.
Two half full stop (..) Indicates the parent directory , For example, path /usr/local/../src Equate to /usr/src, among local and src Catalog peer .

cd The default parameter of the command is , Symbol Represents the home directory of the current user , That is to say root When the user logs in , command cd、cd ~ and cd /root The implementation effect is the same .
touch

Command description :touch The command is used to modify the time attribute of a file or directory , Including access time and change time . If the file does not exist , The system will create a new file .

Command format :touch [ Parameters ] [ file ].

Parameter description :

Parameters explain
-c If the specified file does not exist , No new files will be created
-r Time records using reference documents
-t Set the time record of the file

Command usage example :

Create two empty files .

touch demo1.txt demo2.txt

 Insert picture description here

modify demo1.txt The time of is recorded as the current system time .

 Insert picture description here

to update demo2.txt Time record of , Make it and demo1.txt The time record is the same .

touch -r demo1.txt demo2.txt

 Insert picture description here

mkdir

Command description :mkdir The command is used to create a new subdirectory .-p Parameter to ensure that the directory name exists , Create a new one if it doesn't exist .

mkdir -p a/b/c/d

 Insert picture description here

Command usage example :

new directory a/b/c/d, And use tree Command to view the directory structure after creation .

tree

 Insert picture description here
 Insert picture description here

rm

Command description :rm Command to delete a file or directory .

Command format :rm [ Parameters ] [ file ].

Parameter description :

Parameters explain
-i One by one asked to confirm before deleting
-f No need to confirm , Delete directly
-r Delete all files in the directory

Command usage example :

Delete files directly without confirmation .

rm -rf demo*

 Insert picture description here

Delete directory directly without confirmation a And all subdirectories and files under its directory .

rm -rf a

 Insert picture description here

cp

Command description : cp The command is mainly used to copy files or directories .

Command format :cp [ Parameters ] [ Source file ] [ Target file ].

Parameter description :

Parameters explain
-d When you copy a link reserved
-f Override existing target files without prompting
-i Ask before covering
-p In addition to copying the contents of the file , It also copies the modification time and access rights to the new file
-r Copy the directory and all the items in it

Command usage example :

Put the table of contents c/d Copy everything in to the directory a/b Next .

mkdir -p a/b/c
mkdir -p x/y
cp -r x a/b/c/
tree a

 Insert picture description here

 Insert picture description here

mv

Command description : mv Command to rename a file or directory 、 Or move the file or directory to another location .

Command format :mv [ Parameters ] [ Source file ] [ Target file ]

Parameter description :

Parameters explain
-i If the specified directory already exists file , The first asking to overwrite the old file
-f If the target file already exists , Don't ask and cover directly

Command usage example :

Put the filename a.txt Change it to b.txt.

touch a.txt
mv a.txt b.txt

 Insert picture description here

take a.txt Move to a/b/c/d Next

touch a.txt
mkdir -p a/b/c/d
mv a.txt a/b/c/d/
tree a

 Insert picture description here

Move all the contents of the current directory to /tmp Directory .

mv ./* /tmp tree /tmp 

 Insert picture description here

rename

Command description :rename Command to batch change the file name by string replacement .rename Command has C Language and Perl Two versions of the language , Here are C Language version of rename command , Regular expressions are not supported .

Command usage example :

The string in all file names in the current directory demo Change to uppercase string DEMO.

touch demo1.txt
touch demo2.txt
rename demo DEMO *

 Insert picture description here

Put all... In the current directory .txt The file suffix is changed to text.

rename .txt .text *

 Insert picture description here

ls Commands can be viewed Linux Files on the system 、 Permissions for directories and devices .

ls -l /boot/

 Insert picture description here
Above ls -l The first column displayed in the command is the file permission information , common 11 Bit character , branch 5 part .

 The first 1 Bits indicate the archive type ,d Presentation directory ,- Represents general file .
The first 2~4 Bit indicates the permission of the current user ( The authority of the owner ).
The first 5~7 Bit indicates the user permissions of the same user group ( Group authority ).
The first 8~10 Bits indicate the user permissions of different user groups ( Other user privileges ).
The first 11 Bit is a half full stop ., Express SELinux Safety labels .

There are three users in each group ,rwx Read separately 、 Write 、 Executive authority , The corresponding octal is expressed as 4、2、1.

for example efi The directory root The user rights are drwxr-xr-x..

 The directory is right root The user has all permissions to read, write and execute .
The directory is right root Other users in the group have read and execute permissions .
This directory has read and execute permissions for other users .

Therefore, the corresponding octal permission is expressed as :

 The authority of the owner :4+2+1=7.
Group authority :4+1=5.
Other user privileges :4+1=5.

namely 755.

chmod

chmod The command is used to modify file permissions mode,-R Parameter recursively modifies subdirectories and files .

Command usage example :

New name is hello.sh Of Shell Script , The script will output Hello World. use ll You can see from the command that the newly created script does not have execution permission , Its authority is expressed in octal as 644.

echo "echo 'hello world'" > hello.sh

 Insert picture description here

take hello.sh Add the execution permission of the owner of the file .

chmod u+x hello.sh

 Insert picture description here

take hello.sh Revoke the execution permission of the owner of the file .

chmod u-x hello.sh

 Insert picture description here

take hello.sh Modify the file permission to octal 744 jurisdiction .

chmod 744 hello.sh

 Insert picture description here

Use bash The command interpreter executes hello.sh Script files .

sh hello.sh
bash hello.sh

 Insert picture description here
among ,u+x It means to increase the execution permission of the owner ,u Indicates the owner ,g Indicates a group ,o Means something else ,a Represents all users .

chown command

chown Command to modify the owner and group of the file ;-R Parameter recursively modifies subdirectories and files ;ls -l The third and fourth columns displayed by the command are the owner and group information of the file .

Command usage example :

Create a new text file test.txt, use ll The command can see that the owner and group of the file are root.whoami Command to view the current Shell User name of environment login , establish test user , Change Password , Modify the owner and group

 whoami
touch test.txt
ll
adduser test
passwd test
chown test test.txt
ll
chown admin:admin test.txt
chown test:test test.txt
ll

 Insert picture description here

chgrp command

chgrp The command is used to modify the group of files .

Command usage example :

take test.txt The group of the file is changed to root.

chgrp root test.txt

 Insert picture description here
 Insert picture description here

Alibaba cloud server basic experiment 5 file management commands

cat command .

cat Command description : This command is used to connect files and print to a standard output device .

cat Command syntax :

cat [ Parameters ] [ file name ]

Parameter description :

Parameters explain
-n from 1 Start numbering all output lines .
-b from 1 Start numbering all output lines , Don't number blank lines .
-s When the above encounter with a continuous two lines of blank lines , Just replace it with a blank line .
-E Is displayed at the end of each line $.
-T take TAB Characters appear as ^I.

cat Command usage example

Execute the following command , Write a self increasing sequence to test1.txt In file , And look at

for i in $(seq 1 10); do echo $i >> test1.txt ; done
cat test1.txt

 Insert picture description here

Execute the following command , take test1.txt Add the line number to the content of the file and enter it into test2.txt file .

cat -n test1.txt > test2.txt
cat test2.txt

 Insert picture description here

Execute the following command , take test1.txt Empty file contents .

cat /dev/null > test1.txt
cat test1.txt

 Insert picture description here

cmp

cmp Command description : This command is used to compare two files for differences . When comparing two files are exactly the same as each other , This command does not display any information . Otherwise, the character and column number of the first difference will be marked . When no file name is specified , Or the file name is "-", be cmp Instruction data from the standard input device .

cmp Command syntax :cmp [-clsv][-i < Number of characters >][–help][ First file ][ Second document ]

Parameter description :

Parameters explain
-c In addition to the differences in the decimal character code designated at , Together display the character corresponding to the character .
-i < Number of characters > Specify a number .
-l Designate all the different places .
-s Do not display error messages .
-v Display version information .
–help Online Help .

cmp Command usage example :

Execute the following command , A self increasing sequence 1-5 write in test1.txt In file .

for i in $(seq 1 5); do echo $i >> test1.txt ; done
cat test1.txt

 Insert picture description here

Compare test1.txt Document and test2.txt Whether the documents are the same

cmp test1.txt test2.txt

The return result is as follows , You can see test1.txt Document and test2.txt The first line of the file is different .
 Insert picture description here

diff

diff Command description : This command is used to compare file differences .diff The command is line by line , Compare the similarities and differences between text files . If you specify a directory to compare , be diff Will compare files with the same file name in the directory , But it doesn't compare its subdirectories .

diff Command syntax :diff [ Parameters ] [ File or directory 1] [ File or directory 2]

Parameter description :

Parameters explain
-< Row number > Specifies how many lines of text to display . This parameter must be the same as -c or -u Parameters are used together .
-c Show full text , And mark the differences .
-u Display the difference of file content by merging .
-adiff By default, text files are only compared line by line .
-b Don't check for differences in space characters .
-d Use different algorithms , Compare in smaller units .
-i Don't check for case differences .
-y Show the similarities and differences of files in a side-by-side manner .
-W< Width > In the use of -y When parameters are , Specify column width .

diff Command usage example :

Compare test1.txt Document and test2.txt file , Output in side-by-side format .

diff test1.txt test2.txt -y -W 50

The return result is as follows , You can see test1.txt Document and test2.txt The difference between files .

 Insert picture description here

file

file Command description : This command is used to identify the file type .

file Command syntax :file [ Parameters ] [ file ]

Parameter description :

Parameters explain
-b When listing the identification results , Do not show file name .
-c Detailed display of instruction execution process , A situation that facilitates troubleshooting or analysis of program execution .
-f< Name file > Specify name file , When its content has one or more file names , Give Way file Identify these documents in order , The format is one file name per column .
-L Directly display the category of the file that the symbolic connection points to .
-v Display version information .
-z Read the contents of the compressed file .

file Command usage example :

Show test1.txt file type .

file test1.txt

The return result is as follows , You can see test1.txt File type is ASCII text. Insert picture description here

Show test2.txt The file type does not display the file name .

file -b test2.txt

 Insert picture description here

find command .

find Command description : This command is used to find files in the specified directory . Any string that precedes the parameter is treated as the name of the directory you want to find . If you use the command , Do not set any parameters , be find Command will find subdirectories and files in the current directory . And display all the subdirectories and files found .

find Command syntax :find [ Parameters ] [ file ]

Parameter description :

Parameters explain
-mount Only check the files in the same file system as the specified directory , Avoid other listed file in the file system .
-amin n in the past n Files read in minutes .
-type c File type is c The file of .
-cmin n in the past n Be modified within minutes .
-name name Find file name is name The file of .

find Command usage example :

Suffix all files in the current directory and its subdirectories with .txt The documents of .

find . -name "*.txt"

 Insert picture description here

Find the length of all files in the system as 0 The ordinary documents of , List their full path .

find / -type f -size 0 -exec ls -l {
} \;

 Insert picture description here

 Insert picture description here

copyright:author[Concise programming],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/175/202206240216122339.html