Linux common command learning

Posted by linusx007 on Tue, 15 Feb 2022 04:22:53 +0100

Linux common command learning

1. ls command

It is the abbreviation of list. Through ls command, you can not only view the files contained in linux folders, but also view file permissions (including directory, folder and file permissions)  view directory information, etc.

Common parameter collocation:

ls -a List all files in the directory, including.Start hidden file
ls -A List Division.and..Other documents
ls -r Reverse order arrangement
ls -t Sort by file modification time
ls -S Sort by file size
ls -h Display in readable size
ls -l In addition to the file name, it also lists the permission, owner, file size and other information of the file

example:

(1) Sort in reverse chronological order in a readable manner and display file details

ls -lhrt

(2) Displays file details in reverse order of size

ls -lrS

(3) Lists the details of all directories starting with "t" in the current directory

ls -l t*

(4) List the absolute path of the file (excluding hidden files)

ls | sed "s:^:`pwd`/:"

(5) List the absolute path of the file (including hidden files)

find $pwd -maxdepth 1 | xargs ls -ld

2. cd command

cd(changeDirectory) command syntax:

cd [Directory name]

Description: switch the current directory to dirName.

example:

(1) Enter the directory to

cd /

(2) Enter the "home" directory

cd ~

(3) Enter the last working path

cd -

(4) Use the parameters of the previous command as cd parameters.

cd !$

3. pwd command

The pwd command is used to view the current working directory path.

example:

(1) View current path

pwd

(2) View the actual path of the soft link

pwd -P

4. mkdir command

The mkdir command is used to create folders.

Available options:

  • -m: Set the access permission for the new directory, or use the chmod command;
  • -p: Can be a path name. At this time, if some directories in the path do not exist, after adding this option, the system will automatically establish those directories that do not exist, that is, multiple directories can be established at one time.

example:

(1) Create a folder named t under the current working directory

mkdir t

(2) Create a directory with the path test/t1/t under the tmp directory. If it does not exist, create:

mkdir -p /tmp/test/t1/t

5. rm command

Delete one or more files or directories in a directory. If the - r option is not used, rm will not delete the directory. If you use rm to delete a file, you can usually still restore the file to its original state.

rm [option] File

example:

(1) Delete any log file, ask for confirmation one by one before deleting:

rm -i *.log

(2) Delete the test subdirectory and all files in the subdirectory, and there is no need to confirm one by one:

rm -rf test

(3) Delete files starting with - f

rm -- -f*

6. rmdir command

To delete one or more subdirectory entries from a directory, you must also have write permission to its parent directory when deleting a directory.

Note: non empty directories cannot be deleted

example:

(1) When the parent subdirectory is deleted to make it an empty directory, delete it at the same time:

rmdir -p parent/child/child11

7. mv command

Move the file or modify the file name according to the second parameter type (such as directory, move the file; if it is a file, re command the file).

When the second parameter is a directory, the first parameter can be multiple files or directories separated by spaces, and then move multiple files specified by the first parameter to the directory specified by the second parameter.

example:

(1) Put the file test Log is renamed test1 txt

mv test.log test1.txt

(2) The file Log1 txt,log2. txt,log3. Txt to the root test3 directory

mv llog1.txt log2.txt log3.txt /test3

(3) Rename the file file1 to file2. If file2 already exists, ask whether to overwrite it

mv -i log1.txt log2.txt

(4) Move all files in the current folder to the upper level directory

mv * ../

8. cp command

Copy source files to destination files, or copy multiple source files to destination directories.

Note: when copying from the command line, if the target file already exists, you will be prompted whether to overwrite it. In the shell script, if you do not add the - i parameter, you will not be prompted, but directly overwrite it!

-i Tips
-r Copy the directory and all items in the directory
-a The copied file has the same time as the original file

example:

(1) Copy a.txt to the test directory and keep the original file for a long time. If the original file exists, you will be prompted whether to overwrite it.

cp -ai a.txt test

(2) Create a link (shortcut) for a.txt

cp -s a.txt link_a.txt

9. cat command

cat has three main functions:

1. Display the whole file at one time:

cat filename

2. Create a file from the keyboard:

cat > filename

Only new files can be created, and existing files cannot be edited.

3. Merge several documents into one document:

cat file1 file2 > file
  • -b output line number for non null
  • -n output all line numbers

example:

(1) Put log2012 Add the line number to the file content of log and enter log2013 Log in this file

cat -n log2012.log log2013.log

(2) Put log2012 Log and log2013 Append the contents of the file without adding the blank line number (log) Log

cat -b log2012.log log2013.log log.log

(3) Use here doc to generate a new file

cat >log.txt <<EOF
>Hello
>World
>PWD=$(pwd)
>EOF
ls -l log.txt
cat log.txt
Hello
World
PWD=/opt/soft/test

(4) Reverse listing

tac log.txt
PWD=/opt/soft/test
World
Hello

10. more command

The function is similar to cat. More will be displayed page by page, which is convenient for users to read page by page. The most basic instruction is to press the space key to display the next page, and press the b key to display the back page.

Command parameters:

+n      From the first n Line start display
-n       Define screen size as n that 's ok
+/pattern Search for the string before each file is displayed( pattern),Then start the display after the first two lines of the string 
-c       Clear the screen from the top and display
-d       Hint“ Press space to continue,'q' to quit(Press spacebar to continue, press q Press exit to disable the ringing function
-l        ignore Ctrl+l(Page feed) character
-p       Page change the file by clearing the window instead of scrolling, and-c Similar options
-s       Display consecutive blank lines as one line
-u       Remove the underline from the contents of the document

Common operation commands:

Enter    down n Line, need to be defined. The default is 1 line
Ctrl+F   Scroll down one screen
 Space bar scroll down one screen
Ctrl+B  Return to previous screen
=       Output the line number of the current line
:f     Output file name and line number of the current line
V      call vi editor 
!Command call Shell,And execute the command
q       sign out more

example:

(1) Displays the contents of the file starting from line 3

more +3 text.txt

(2) In the detailed information of the listed file directory, use the pipeline to display 5 lines at a time

ls -l | more -5

Press the space to display the next 5 lines.

11. less command

Less is similar to more, but with less, you can browse the file at will, while more can only move forward, but not backward, and less will not load the whole file before viewing.

Common command parameters:

-i  Ignore case when searching
-N  Displays the line number of each line
-o  <file name> take less The output content is saved in the specified file
-s  Displays a row of consecutive empty lines
/String: the ability to drill down on "string"
?String: the ability to search up for "string"
n: Repeat previous search (and / or ? Relevant)
N: Reversely repeats the previous search (and / or ? Relevant)
-x <number> Will“ tab"The key is displayed as a specified number space
b  Turn back one page
d  Turn back half a page
h  Display help interface
Q  sign out less command
u  Scroll forward half a page
y  Scroll forward one line
 Space bar to scroll one line
 Press enter to scroll through the page
[pagedown]:  Turn down a page
[pageup]:    Turn up a page

example:

(1) ps view the process information and display it in less pages

ps -aux | less -N

(2) View multiple files

less 1.log 2.log

You can use n to see the next one and p to see the previous one.

12. head command

Head is used to display the beginning of the file to the standard output. The default head command prints the first 10 lines of its corresponding file.

Common parameters:

-n<Number of rows> Number of lines displayed (the number of lines is a complex number, indicating the number from the last to the front)

example:

(1) Display 1 The first 20 lines in the log file

head 1.log -n 20

(2) Display 1 First 20 bytes of log file

head -c 20 log2014.log

(3) Display the last 10 lines of t.log

head -n -10 t.log

13. tail command

It is used to display the contents at the end of the specified file. If the file is not specified, it will be processed as input information. Common view log files.

Common parameters:

-f Circular reading (often used to view incremental log files)
-n<Number of rows> Display rows (from back to front)

(1) Cyclic reading of increasing file contents

ping 127.0.0.1 > ping.log &

Background operation: you can use jobs -l to view it or fg to move it to the foreground for operation.

tail -f ping.log

(view log)

14. which command

To find a file in linux, but do not know where it is, you can use the following commands to search:

which     View the location of the executable.
whereis View the location of the file.
locate  Check the file location with the database.
find        Actually search the hard disk to query the file name.

Which is to search the location of a system command in the specified PATH and return the first search result. Using the which command, you can see whether a system command exists and where the command is executed.

Common parameters:

-n  Specify the length of the file name. The specified length must be greater than or equal to the longest file name in all files.

example:

(1) Check whether the ls command exists and which one to execute

which ls

(2) View which

which which

(3) View cd

which cd(The display does not exist because cd It's a built-in command, and which Find display yes PATH (commands in)

To view the current PATH configuration:

echo $PATH

Or use env to view all environment variables and their corresponding values

15. whereis command

The whereis command can only be used to search for program names, and only binary files (parameter - b), man description files (parameter - m), and source code files (parameter - s) are searched. If the parameter is omitted, all information is returned. Both whereis and locate are based on the built-in database of the system, so they are very efficient, while find is to traverse the hard disk to find files.

Common parameters:

-b   Locate the executable.
-m   Locate the help file.
-s   Locate the source code file.
-u   Search for files other than executable files, source code files and help files in the default path.

example:

(1) Find files related to the locate program

whereis locate

(2) Find the source file of locate

whereis -s locate

(3) Find help files for lcoate

whereis -m locate

16. locate command

Locate can quickly find files by searching the built-in document database of the system. The database is updated by updatedb program, which is called periodically by cron daemon. By default, the locate command searches the database faster than the whole hard disk data, but the worse thing is that the files found by locate may not be found if they have been recently established or just renamed. In the internal setting, updatedb runs once a day, and the set value (etc/crontab) can be updated by modifying the crontab.

The locate command is similar to the find command and can be used, such as *? And so on

Common parameters:

-l num((number of rows to display)
-f   Exclude specific filing systems, such as proc be excluded
-r   Using regular expressions as search conditions

example:

(1) Find all files related to pwd (including pwd in the file name)

locate pwd

(2) Search all files starting with sh in the etc directory

locate /etc/sh

(3) Find the file ending with reason in the / var directory

locate -r '^/var.*reason$'(among.Represents a character,*Indicates multiple tasks;.*Represents any number of characters)

17. find command

It is used to find files in the file tree and make corresponding processing.

Command format:

find pathname -options [-print -exec -ok ...]

Command parameters:

pathname: find The directory path found by the command. For example, use.To represent the current directory, using/To represent the system root directory.
-print:  find The command outputs matching files to standard output.
-exec:  find The command executes the command given by this parameter on the matching file shell Command. The form of the corresponding command is'command' {  } \;,be careful{   }and\;Space between.
-ok:  and-exec The function is the same, except that the given by this parameter is executed in a safer mode shell Before executing each command, the user will be prompted to determine whether to execute it.

Command options:

-name Find files by file name
-perm Find files by file permissions
-user Find files by file owner
-group  Find files by the group to which they belong.
-type  Find a certain type of file, such as:
   b - Block device file
   d - catalogue
   c - Character device file
   l - Symbolic link file
   p - Pipeline file
   f - Ordinary file

-size n :[c] Find file length is n Block file with c Time table file byte size
-amin n   Find the last in the system N Files accessed in minutes
-atime n  Find the last in the system n*24 Files accessed in hours
-cmin n   Find the last in the system N Minutes to change the status of the file
-ctime n  Find the last in the system n*24 Files whose status has been changed for hours
-mmin n   Find the last in the system N Minutes of file data changed
-mtime n  Find the last in the system n*24 Files with changed file data for hours
(Use minus sign-To limit the change time from now on n For documents within days, use the plus sign instead+To limit the change time from now on n Documents before date. )
-maxdepth n Maximum lookup directory depth
-prune Option to indicate which directories need to be ignored. in use-prune Be careful when choosing Options, because if you use both-depth Option, then-prune Options will be find Command ignore
-newer If you want to find all files whose change time is newer than one file but older than another, you can use-newer option

example:

(1) Find files modified within 48 hours

find -atime -2

(2) Find in the current directory to log file Represents the current directory

find ./ -name '*.log'

(3) Find the file with permission of 777 in the / opt directory

find /opt -perm 777

(4) Find files larger than 1K

find -size +1000c

Find files equal to 1000 characters

find -size 1000c 

-The exec parameter is followed by the command command, which terminates with; The semicolon after this command is indispensable because it marks the end. Considering that the semicolon will have different meanings in each system, a backslash is added in front of it. {} curly brackets represent the file name found in the front find.

example:

(5) Find them in the current directory and delete them in the last 10 days without a reminder

find . -type f -mtime +10 -exec rm -f {} \;

(6) Find all file names in the current directory to log end, change files with a time of more than 5 days, and delete them, but give a prompt before deleting. Press the y key to delete the file, and press the n key not to delete it

find . -name '*.log' mtime +5 -ok -exec rm {} \;

(7) Find the file whose name starts with passwd and whose content contains the character "pkg" in the current directory

find . -f -name 'passwd*' -exec grep "pkg" {} \;

(8) Execute cp command with exec option

find . -name '*.log' -exec cp {} test3 \;

-The xargs find command passes the matched files to the xargs command, and the xargs command only gets some files at a time instead of all, unlike the - exec option. In this way, it can process the first part of the files obtained, then the next batch, and continue like this.

example:

(9) Find each ordinary file in the current directory, and then use xargs to judge the file type

find . -type f -print | xargs file

(10) Find all ordinary files ending in js and containing the character 'editor' in the current directory

find . -type f -name "*.js" -exec grep -lF 'ueditor' {} \;
find -type f -name '*.js' | xargs grep -lF 'editor'

(11) Using xargs to execute mv command

find . -name "*.log" | xargs -i mv {} test4

(12) Use the grep command to search for the word hostnames in all ordinary files in the current directory and mark the line:

find . -name \*((escape) -type f -print | xargs grep -n 'hostnames'

(13) Find the current directory that begins with a lowercase letter and ends with 4 to 9 plus log ended file:

find . -name '[a-z]*[4-9].log' -print

(14) Search in the test directory, not in the test4 subdirectory

find test -path 'test/test4' -prune -o -print

(15) Example 1: find the change time is longer than the file log2012 Log is newer than the file log2017 Log old files

find -newer log2012.log ! -newer log2017.log

Use the depth option:

The depth option enables the find command to back up the file system on tape. You want to back up all files first, and then back up the files in the subdirectory.

Example: the find command starts from the root directory of the file system and finds a file named con File. It will first match all the files and then look in the subdirectory

find / -name "CON.FILE" -depth -print

18. chmod command

Used to change the access rights of linux system files or directories. Use it to control access to files or directories. This command has two uses. One is the text setting method including letters and operator expressions; Another way to set numbers is to include numbers.

There are three groups of access permissions for each file or directory. Each group is represented by three digits, which are the read, write and execution permissions of the owner of the file; Read, write and execute permissions of users in the same group as the owner; Read, write and execute permissions of other users in the system. You can use LS - L test Txt search.

In the form of file log2012 Log as an example:

-rw-r--r-- 1 root root 296K 11-13 06:03 log2012.log

The first column has 10 positions, and the first character specifies the file type. In the usual sense, a directory is also a file. If the first character is a horizontal line, it indicates that it is a non directory file. If d, it means a directory. From the second character to the tenth nine characters, a group of three characters represents the permissions of three groups of users on files or directories respectively. Permission characters use horizontal lines to represent empty permission, r for read-only, w for write, and x for executable.

Common parameters:

-c Report processing information when changes occur
-R Process all files in the specified directory and its subdirectories

Scope of authority:

u : Current user of the directory or file
g : Current group of directories or files
o : A user or group other than the current user or group of a directory or file
a : All users and groups

Permission code:

r : Read permission, represented by the number 4
w : Write permission, represented by the number 2
x : Execution Authority, represented by the number 1
- : Delete permission, represented by the number 0
s : special competencies

example:

(1) Add executable permissions for all users of the file t.log

chmod a+x t.log

(2) Revoke all the original permissions, then make the owner have readable permissions, and output processing information

chmod u=r t.log -c

(3) Assign read, write and execute (7) permissions to the owner of the file, assign read and execute (5) permissions to the group where the file belongs, and assign execute (1) permissions to other users

chmod 751 t.log -c(Or: chmod u=rwx,g=rx,o=x t.log -c)

(4) Add readable permissions to all files in the test directory and its subdirectories

chmod u+r,g+r,o+r -R text/ -c

19. tar command

Used to compress and decompress files. tar itself has no compression function, only packaging function. Compression and decompression are completed by calling other functions.

Clarify two concepts: packaging and compression. Packaging refers to turning a large number of files or directories into a total file; Compression is to turn a large file into a small file through some compression algorithms

Common parameters:

-c Create a new compressed file
-f Specify compressed file
-r Add files to an already compressed package
-u Add modified and existing files to the compressed package
-x Extract files from compressed packages
-t Displays the contents of the compressed file
-z support gzip compress
-j support bzip2 compress
-Z support compress Unzip file
-v Display operation process

For gzip and bzip2 compression:

gzip Instance: compression gzip fileName .tar.gz and.tgz  Decompression: gunzip filename.gz or gzip -d filename.gz
          corresponding: tar zcvf filename.tar.gz     tar zxvf filename.tar.gz

bz2 Instance: compression bzip2 -z filename .tar.bz2 Decompression: bunzip filename.bz2 or bzip -d filename.bz2
       corresponding: tar jcvf filename.tar.gz         Decompression: tar jxvf filename.tar.bz2

example:

(1) Package all files into tar package

tar -cvf log.tar 1.log,2.log or tar -cvf log.*

(2) Package all files and directories in / etc to the specified directory and use gz compression

tar -zcvf /tmp/etc.tar.gz /etc

(3) View the contents of the file just packaged (z must be added, because it is compressed using gzip)

tar -ztvf /tmp/etc.tar.gz

(4) To compress / home, /etc, but not / home/dmtsai

tar --exclude /home/dmtsai -zcvf myfile.tar.gz /home/* /etc

20. chown command

chown changes the owner of the specified file to the specified user or group. The user can be a user name or user ID; A group can be a group name or a group ID; Files are separated by spaces. The list of files to change permissions supports wildcards.

-c Displays information about the changed section
-R Handle specified directories and subdirectories

example:

(1) Change owners and groups and display change information

chown -c mail:mail log2012.log

(2) Change file group

chown -c :mail t.log

(3) Change the folder and sub file directory to mail

chown -cR mail: test/

21. df command

Displays disk space usage. Get the information such as how much space the hard disk is occupied and how much space is left at present. If no file name is specified, the available space of all currently mounted file systems will be displayed. By default, disk space is displayed in 1KB, unless the environment variable POSIXLY_CORRECT is specified so that it will be displayed in 512 bytes:

-a List of all file systems
-h Display information in a readable manner
-i display inode information
-k The block is 1024 bytes
-l Show only local disks
-T List file system types

example:

(1) Display disk usage

df -l

(2) List all file systems and their types in a readable manner

df -haT

22. du command

The du command is also used to view the space used, but unlike the df command, the Linux du command is used to view the space used by files and directory disks:

Command format:

du [option] [file]

Common parameters:

-a Displays the size of all files in the directory
-k with KB Displays the file size in units
-m with MB Displays the file size in units
-g with GB Displays the file size in units
-h Displays the file size in a readable manner
-s Show totals only
-c or--total  In addition to displaying the size of individual directories or files, it also displays the sum of all directories or files

example:

(1) Displays the size of folders and subfolders in a readable manner

du -h scf/

(2) Displays all file sizes in the folder in a readable manner

du -ah scf/

(3) Displays the disk space occupied by several files or directories, and counts their total

du -hc test/ scf/

(4) Output the space used by each subdirectory under the current directory

du -hc --max-depth=1 scf/

23. ln command

The function is to establish a synchronous link for files in another location. When this problem is needed in different directories, it is not necessary to create the same file for each directory, and reduce the disk consumption through the link created by ln.

Link classification: software link and hard link

Soft link:

  • 1. Soft links exist in the form of paths. Similar to shortcuts in Windows operating system
  • 2. Soft links can cross file systems, but hard links cannot
  • 3. Soft link can link a nonexistent file name
  • 4. Soft link can link the directory

Hard link:

  • 1. Hard links exist in the form of copies of documents. But it doesn't take up the actual space.
  • 2. Hard links to directories are not allowed
  • 3. Hard links can only be created in the same file system

Note:

  • First: the ln command will keep the synchronization of each linked file, that is, no matter where you change, other files will change the same;
  • Second: the link of LN can be divided into soft link and hard link. Soft link is ln – s source file and target file. It will only generate a file image at the location you selected and will not occupy disk space. Hard link ln source file and target file. Without the parameter - s, it will generate a file with the same size as the source file at the location you selected, Whether it is soft link or hard link, the file changes synchronously.
  • Third: ln instruction is used to link files or directories. If more than two files or directories are specified at the same time, and the last destination is an existing directory, all the files or directories specified above will be copied to the directory. If multiple files or directories are specified at the same time, and the last destination is not an existing directory, an error message will appear.

Common parameters:

-b Delete, overwrite previously established links
-s Soft link (symbolic link)
-v Show detailed processing

example:

(1) Create a soft link to the file and display the operation information

ln -sv source.log link.log

(2) Create a hard link to the file and display the operation information

ln -v source.log link1.log

(3) Create soft links to directories

ln -sv /opt/soft/test/test3 /opt/soft/test/test5

24. date command

Displays or sets the date and time of the system.

Command parameters:

-d<character string>  Displays the date and time to which the string refers. The string must be enclosed in double quotation marks.
-s<character string>  Set the date and time based on the string. The string must be preceded by double quotes.
-u  display GMT. 
%H hour(00-23)
%I hour(00-12)
%M minute(With 00-59 To show)
%s Total seconds. The starting time is 1970-01-01 00:00:00 UTC. 
%S second(Expressed in local idioms)
%a Abbreviation for week.
%A Full name of the week.
%d date(With 01-31 To show). 
%D date(Including mm / DD / yy). 
%m month(With 01-12 To show). 
%y particular year(With 00-99 To show). 
%Y particular year(Expressed in four digits). 

example:

(1) Show next day

date +%Y%m%d --date="+1 day"  //Displays the date of the next day

(2) - d parameter usage

date -d "nov 22"  November 22 this year is Wednesday
date -d '2 weeks' 2 Date after week
date -d 'next monday' (Next Monday's date)
date -d next-day +%Y%m%d(Tomorrow's date) or: date -d tomorrow +%Y%m%d
date -d last-day +%Y%m%d(Yesterday's date) Or: date -d yesterday +%Y%m%d
date -d last-month +%Y%m(What month was last month)
date -d next-month +%Y%m(What month is next)

25. cal command

You can display the Gregorian calendar (Gregorian calendar). If there is only one parameter, it indicates the year (1-9999). If there are two parameters, it indicates the month and year:

Common parameters:

-3 Displays the calendar of the previous month, the current month and the next month
-m Show Monday as the first column
-j Displays the day ordinal of the current year
-y [year]Displays the current year[year]Copy of calendar

example:

(1) Displays the specified month, year and date

cal 9 2012

(2) Displays the calendar of each month in 2013

cal -y 2013

(3) Take Monday as the first column to display the first, middle and last three months

cal -3m

26. grep command

Powerful text search command, grep(Global Regular Expression Print) global regular expression search.

grep works by searching for string templates in one or more files. If the template includes spaces, it must be referenced, and all strings after the template are regarded as file names. The search results are sent to the standard output without affecting the content of the original file.

Command format:

grep [option] pattern file|dir

Common parameters:

-A n --after-context After displaying matching characters n that 's ok
-B n --before-context Before displaying matching characters n that 's ok
-C n --context Display before and after matching characters n that 's ok
-c --count Calculate the number of columns that match the style
-i ignore case
-l Only the file names whose contents conform to the specified style are listed
-f Read keywords from file
-n Displays the number of lines in the file where the matching content is located
-R Recursively find folders

Regular expression of grep:

^  #The beginning of the anchor line, such as' ^ grep 'matches all lines beginning with grep. 
$  #Anchor the end of the line, such as: 'grep $' matches all lines ending in grep. 
.  #Matches a non newline character, such as: 'gr.p' matches GR followed by an arbitrary character, followed by P.  
*  #Matches zero or more previous characters, such as' * grep 'matches all one or more spaces followed by the line of grep.
.*   #Used together to represent any character.  
[]   #Matches characters within a specified range, such as' [Gg]rep 'matches grep and grep. 
[^]  #Matches a character that is not within the specified range, such as' [^ A-FH-Z]rep 'matches a line that begins with a letter that does not contain A-R and T-Z, followed by Rep.  
\(..\)  #Mark matching characters, such as' \ (love \) ', and love is marked as 1.   
\<      #Anchor the beginning of the word, such as' \ < grep 'matches the line containing the word beginning with grep.
\>      #Anchor the end of the word, such as' grep \ > 'to match the line containing the word ending in grep.
x\{m\}  #Repeat the character x, m times, for example: '0 \ {5 \}' matches the line containing 5 o's. 
x\{m,\}  #Repeat the character x at least m times. For example, 'o\{5, \}' matches a line with at least 5 o's.  
x\{m,n\}  #Repeat the character x at least m times and no more than n times. For example, 'o\{5,10 \}' matches 5-10 o lines.  
\w    #Match text and numeric characters, i.e. [A-Za-z0-9], for example: 'G\w*p' matches G followed by zero or more text or numeric characters, followed by P.  
\W    #\The inverted form of w matches one or more non word characters, such as period, period, etc.  
\b    #Word lock, such as' \ bgrep\b 'only matches grep.

example:

(1) Find the specified process

ps -ef | grep svn

(2) Find the number of specified processes

ps -ef | grep svn -c

(3) Read keywords from file

cat test1.txt | grep -f key.log

(4) Recursively find lines starting with grep from folders and list only files

grep -lR '^grep' /tmp

(5) Find row contents of non-x switch

grep '^[^x]' test.txt

(6) Displays the content line containing the ed or at character

grep -E 'ed|at' test.txt

27. wc command

wc(word count) function is to count the number of bytes, words and lines in the specified file, and output the statistical results

Command format:

wc [option] file..

Command parameters:

-c Count bytes
-l Count rows
-m Count characters
-w Count the number of words. A word is defined as a string separated by blank, skip, or newline characters

example:

(1) Find the number of lines in the file word number section file name

wc text.txt

result:

7     8     70     test.txt

(2) Count the number of rows of the output result

cat test.txt | wc -l

28. ps command

ps(process status) is used to view the current running process status. It can be viewed at one time. If dynamic continuous results are needed, use top

Processes on linux have five states:

  • \1. Run (running or waiting in the run queue)
  • \2. Interrupt (in sleep, blocked, waiting for the formation of a condition or receiving a signal)
  • \3. Non interruptible (the process cannot wake up and run after receiving the signal, and the process must wait until an interrupt occurs)
  • \4. Dead (the process has been terminated, but the process descriptor exists until it is released after the parent process calls wait4() system call)
  • \5. Stop (the process stops running after receiving sigstop, sigstp, sigtin and sigtou signals)

ps tool identifies five status codes of the process:

D Non interruptible uninterruptible sleep (usually IO)
R function runnable (on run queue)
S interrupt sleeping
T stop it traced or stopped
Z dead a defunct ("zombie") process

Command parameters:

-A Show all processes
a Show all processes
-a Display all processes under the same terminal
c Displays the real name of the process
e Show environment variables
f Show relationships between processes
r Displays the processes currently running on the terminal
-aux Displays all processes that contain other uses

example:

(1) Displays all current process environment variables and inter process relationships

ps -ef

(2) Show all current processes

ps -A

(3) Use with grep to find a process

ps -aux | grep apache

(4) Find out the PID numbers related to cron and syslog services

ps aux | grep '(cron|syslog)'

29. top command

Displays information about the process currently being executed by the system, including process ID, memory usage, CPU usage, etc

Common parameters:

-c Displays the complete process command
-s Confidentiality mode
-p <Process number> Specify process display
-n <frequency>Cycle display times

example:

(1)

top - 14:06:23 up 70 days, 16:44,  2 users,  load average: 1.25, 1.32, 1.35
Tasks: 206 total,   1 running, 205 sleeping,   0 stopped,   0 zombie
Cpu(s):  5.9%us,  3.4%sy,  0.0%ni, 90.4%id,  0.0%wa,  0.0%hi,  0.2%si,  0.0%st
Mem:  32949016k total, 14411180k used, 18537836k free,   169884k buffers
Swap: 32764556k total,        0k used, 32764556k free,  3612636k cached
PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND  
28894 root      22   0 1501m 405m  10m S 52.2  1.3   2534:16 java  

The first five lines are the overall statistical information area of the current system.

The first line, task queue information, is the same as the execution result of uptime command. The specific parameters are described as follows:

14: 06:23 - current system time

up 70 days, 16:44 - the system has been running for 70 days, 16 hours and 44 minutes (the system has not been restarted during this period!)

2 users - there are currently 2 users logged into the system

load average: 1.15, 1.42, 1.44 - the following three numbers of load average are the load conditions of 1 minute, 5 minutes and 15 minutes respectively.

load average data is the number of active processes checked every 5 seconds, and then calculated according to a specific algorithm. If this number is divided by the number of logical CPU s, when the result is higher than 5, it indicates that the system is overloaded.

In the second line, Tasks - Tasks (processes). The specific information is as follows:

The system now has a total of 206 processes, including 1 in operation, 205 in sleep, 0 in stopped state and 0 in zombie state (zombie).

The third line is cpu status information. The specific attributes are described as follows:

5.9%us — User space occupation CPU Percentage of.
3.4% sy — Kernel space occupation CPU Percentage of.
0.0% ni — Occupied by processes with changed priority CPU Percentage of
90.4% id — free CPU percentage
0.0% wa — IO Waiting for occupation CPU Percentage of
0.0% hi — Hard interrupt( Hardware IRQ)occupy CPU Percentage of
0.2% si — Soft interrupt( Software Interrupts)occupy CPU Percentage of

**Note: * * the CPU usage ratio here is different from the concept of windows. You need to understand the relevant knowledge of linux system user space and kernel space!

The fourth line, memory status, details are as follows:

32949016k total — Total physical memory (32) GB)
14411180k used — Total memory in use (14) GB)
18537836k free — Total free memory (18) GB)
169884k buffers — Amount of memory cached (169) M)

In the fifth line, swap exchanges partition information. The specific information is as follows:

32764556k total — Total exchange area (32) GB)
0k used — Total swap area used (0) K)
32764556k free — Total free swap area (32) GB)
3612636k cached — Total number of swap buffers (3).6GB)

Sixth line, blank line.

The seventh line is as follows: the status monitoring of each process (task), and the information of the item column is described as follows:

PID — process id
USER — Process owner
PR — Process priority
NI — nice Value. Negative values indicate high priority and positive values indicate low priority
VIRT — Total amount of virtual memory used by the process, in kb. VIRT=SWAP+RES
RES — The size of physical memory used by the process and not swapped out, unit: kb. RES=CODE+DATA
SHR — Shared memory size in kb
S — Process status. D=A state of uninterrupted sleep R=function S=sleep T=track/stop it Z=Zombie process
%CPU — From last update to now CPU Time occupancy percentage
%MEM — Percentage of physical memory used by the process
TIME+ — Used by the process CPU Total time, unit 1/100 second
COMMAND — Process name (command name)/(command line)

top interactive command

h display top Interactive command help information
c Toggles the display of the command name and the full command line
m Sort by memory usage
P according to CPU Sort using percentage size
T According to time/Sort by cumulative time
W Write current settings to~/.toprc In the file
o perhaps O Change the order in which items are displayed

30. kill Command

Send the specified signal to the corresponding process. If the model is not specified, SIGTERM (15) will be sent to terminate the specified process. If the program cannot be terminated, the "- KILL" parameter can be used, and the signal sent by it is SIGKILL(9), which will forcibly end the process. Use ps command or jobs command to view the process number. The root user will affect the user's process, and the non root user can only affect his own process.

Common parameters:

-l  Signal. If the number parameter of the signal is not added, it is used“-l"The parameter lists all signal names
-a  When processing the current process, the correspondence between the command name and the process number is not limited
-p  appoint kill The command only prints the process number of the relevant process without sending any signal
-s  Specify send signal
-u  Designated user

example:

(1) First use ps to find the process pro1, and then kill it with kill

kill -9 $(ps -ef | grep pro1)

31. free command

Displays the system memory usage, including physical memory, swap memory and kernel buffer memory.

Command parameters:

-b with Byte Display memory usage
-k with kb Displays memory usage in units
-m with mb Displays memory usage in units
-g with gb Displays memory usage in units
-s<Interval seconds> Continuous display memory
-t Displays the total memory usage

example:

(1) Display memory usage

free
free -k
free -m

(2) Displays memory usage information in the form of a sum

free -t

(3) Periodically query memory usage

free -s 10

Original address: https://www.cnblogs.com/gaojun/p/3359355.html

Topics: Linux shell