1. ls command

It is the abbreviation of list. With the ls command, you can not only view the files contained in a Linux folder, but also view file permissions (including directory, folder, and file permissions), directory information, and so on.

Common parameter combinations:

ls -a 列出目录所有文件,包含以.开始的隐藏文件
ls -A 列出除.及..的其它文件
ls -r 反序排列
ls -t 以文件修改时间排序
ls -S 以文件大小排序
ls -h 以易读大小显示
ls -l 除了文件名之外,还将文件的权限、所有者、文件大小等信息详细列出来

Examples:

(1) Sort in reverse chronological order in a human-readable way, and display detailed file information

ls -lhrt

(2) Display detailed file information in reverse order of size

ls -lrS

(3) List the detailed contents of all directories starting with "t" in the current directory

ls -l t*

(4) List absolute paths of files (not including hidden files)

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

(5) List absolute paths of files (including hidden files)

find $pwd -maxdepth 1 | xargs ls -ld

2. cd command

cd (changeDirectory) command syntax:

cd [目录名]

Description: Switch the current directory to dirName.

Examples:

(1) Enter the required directory

cd /

(2) Enter the "home" directory

cd ~

(3) Enter the previous working directory

cd -

(4) Use the previous command's argument as the cd parameter.

cd !$

3. pwd command

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

Examples:

(1) View the current path

pwd

(2) View the actual path of a symbolic link

pwd -P

4. mkdir command

The mkdir command is used to create folders.

Available options:

  • -m: Set access permissions for newly created directories; you can also use the chmod command to set them;
  • -p: Can be a path name. At this point, if some directories in the path do not exist yet, after adding this option, the system will automatically create those non-existing directories, meaning multiple directories can be created at once.

Examples:

(1) Create a folder named t in 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 it:

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 directories. If you use rm to delete files, they can usually still be restored to their original state.

rm [选项] 文件…

Examples:

(1) Delete any .log files, asking for confirmation one by one before deletion:

rm -i *.log

(2) Delete the test subdirectory and all files in the subdirectory without confirming one by one:

rm -rf test

(3) Delete files starting with -f

rm -- -f*

6. rmdir command

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

Note: Cannot delete non-empty directories

Examples:

(1) If the parent subdirectory becomes an empty directory after being deleted, then delete it along with it:

rmdir -p parent/child/child11

7. mv command

Move files or modify file names, depending on the type of the second argument (if it is a directory, the file is moved; if it is a file, the file is renamed).

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

Examples:

(1) Rename the file test.log to test1.txt

mv test.log test1.txt

(2) Move the files log1.txt, log2.txt, log3.txt to the test3 directory in the root

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

(3) Rename file1 to file2; if file2 already exists, ask whether to overwrite

mv -i log1.txt log2.txt

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

mv * ../

8. cp command

Copy source files to a target file, or copy multiple source files to a target directory.

Note: When copying on the command line, if the target file already exists, you will be prompted whether to overwrite. However, in shell scripts, if the -i parameter is not added, there will be no prompt; instead, it will overwrite directly!

-i 提示
-r 复制目录及目录内所有项目
-a 复制的文件与原文件时间一样

Examples:

(1) Copy a.txt to the test directory, preserve the original file time, and if the original file exists, prompt whether to overwrite.

cp -ai a.txt test

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

cp -s a.txt link_a.txt

9. cat command

cat mainly has three major functions:

1. Display the entire file at once:

cat filename

2. Create a file from the keyboard:

cat > filename

It can only create new files, not edit existing files.

3. Merge several files into one file:

cat file1 file2 > file
  • -b Output line numbers on non-empty lines
  • -n Output all line numbers

Examples:

(1) Add line numbers to the contents of log2012.log and write them into the file log2013.log

cat -n log2012.log log2013.log

(2) Add line numbers to the contents of log2012.log and log2013.log (blank lines without line numbers), then append the content to log.log

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

(3) Use a here document 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

Its function is similar to cat, but more displays content page by page, making it convenient for users to read page by page. The most basic instruction is to press the space bar to display the next page, and press the b key to go back one page.

Command parameters:

+n      从笫 n 行开始显示
-n       定义屏幕大小为n行
+/pattern 在每个档案显示前搜寻该字串(pattern),然后从该字串前两行之后开始显示 
-c       从顶部清屏,然后显示
-d       提示“Press space to continue,’q’ to quit(按空格键继续,按q键退出)”,禁用响铃功能
-l        忽略Ctrl+l(换页)字符
-p       通过清除窗口而不是滚屏来对文件进行换页,与-c选项相似
-s       把连续的多个空行显示为一行
-u       把文件内容中的下画线去掉

Common operation commands:

Enter    向下 n 行,需要定义。默认为 1 行
Ctrl+F   向下滚动一屏
空格键  向下滚动一屏
Ctrl+B  返回上一屏
=       输出当前行的行号
:f     输出文件名和当前行的行号
V      调用vi编辑器
!命令   调用Shell,并执行命令
q       退出more

Examples:

(1) Display the content of the file starting from line 3

more +3 text.txt

(2) When listing detailed information of file directories, use a pipe to display 5 lines at a time

ls -l | more -5

Press space to display the next 5 lines.

11. less command

less is similar to more, but with less you can browse files freely, while more can only move forward and cannot move backward. Moreover, less does not load the entire file before viewing.

Common command parameters:

-i  忽略搜索时的大小写
-N  显示每行的行号
-o  <文件名> 将less 输出的内容在指定文件中保存起来
-s  显示连续空行为一行
/字符串:向下搜索“字符串”的功能
?字符串:向上搜索“字符串”的功能
n:重复前一个搜索(与 / 或 ? 有关)
N:反向重复前一个搜索(与 / 或 ? 有关)
-x <数字> 将“tab”键显示为规定的数字空格
b  向后翻一页
d  向后翻半页
h  显示帮助界面
Q  退出less 命令
u  向前滚动半页
y  向前滚动一行
空格键 滚动一行
回车键 滚动一页
[pagedown]: 向下翻动一页
[pageup]:   向上翻动一页

Examples:

(1) Use ps to view process information and display it page by page through less

ps -aux | less -N

(2) View multiple files

less 1.log 2.log

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

12. head command

head is used to display the beginning of a file to standard output. By default, the head command prints the first 10 lines of the corresponding file.

Common parameters:

-n<行数> 显示的行数(行数为复数表示从最后向前数)

Examples:

(1) Display the first 20 lines of the 1.log file

head 1.log -n 20

(2) Display the first 20 bytes of the 1.log file

head -c 20 log2014.log

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

head -n -10 t.log

13. tail command

Used to display the end of a specified file. When no file is specified, it processes input information. Commonly used for viewing log files.

Common parameters:

-f 循环读取(常用于查看递增的日志文件)
-n<行数> 显示行数(从后向前)

(1) Loop to read the gradually increasing content of a file

ping 127.0.0.1 > ping.log &

Run in the background: You can use jobs -l to view it, or use fg to move it to the foreground and run it.

tail -f ping.log

(View logs)

14. which command

To find a file in Linux when you don't know where it is, you can use some of the following commands to search:

which     查看可执行文件的位置。
whereis 查看文件的位置。
locate  配合数据库查看文件位置。
find        实际搜寻硬盘查询文件名称。

which searches for the location of a system command in the path specified by PATH, and returns the first search result. Using the which command, you can see whether a system command exists and which location's command is actually executed.

Common parameters:

-n  指定文件名长度,指定的长度必须大于或等于所有文件中最长的文件名。

Examples:

(1) Check whether the ls command exists and which one is executed

which ls

(2) Check the which command

which which

(3) Check the cd command

which cd(显示不存在,因为 cd 是内建命令,而 which 查找显示是 PATH 中的命令)

Check 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 it only searches binary files (option -b), man documentation files (option -m), and source code files (option -s). If the option is omitted, all information is returned. Both whereis and locate search based on the system's built-in database, so they are highly efficient, while find traverses the hard disk to find files.

Common options:

-b   定位可执行文件。
-m   定位帮助文件。
-s   定位源代码文件。
-u   搜索默认路径下除可执行文件、源代码文件、帮助文件以外的其它文件。

Examples:

(1) Find files related to the locate program

whereis locate

(2) Find the source code files of locate

whereis -s locate

(3) Find the help file for lcoate

whereis -m locate

16. locate command

locate quickly finds files by searching the system's built-in document database. The database is updated by the updatedb program, which is periodically invoked by the cron daemon. By default, the locate command searches the database faster than searching through the entire hard disk data, but the downside is that files recently created or just renamed may not be found. By default, updatedb runs once a day; you can modify crontab to update the settings (etc/crontab).

The locate command is similar to the find command; it can use regular expression matching such as * and ?.

Common options:

-l num(要显示的行数)
-f   将特定的档案系统排除在外,如将proc排除在外
-r   使用正则运算式做为寻找条件

Examples:

(1) Find all files related to pwd (file names containing pwd)

locate pwd

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

locate /etc/sh

(3) Find files ending with reason under the /var directory

locate -r '^/var.*reason$'(其中.表示一个字符,*表示任务多个;.*表示任意多个字符)

17. find command

Used to find files in the file tree and perform corresponding processing.

Command format:

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

Command parameters:

pathname: find命令所查找的目录路径。例如用.来表示当前目录,用/来表示系统根目录。
-print: find命令将匹配的文件输出到标准输出。
-exec: find命令对匹配的文件执行该参数所给出的shell命令。相应命令的形式为'command' {  } \;,注意{   }和\;之间的空格。
-ok: 和-exec的作用相同,只不过以一种更为安全的模式来执行该参数所给出的shell命令,在执行每一个命令之前,都会给出提示,让用户来确定是否执行。

Command options:

-name 按照文件名查找文件
-perm 按文件权限查找文件
-user 按文件属主查找文件
-group  按照文件所属的组来查找文件。
-type  查找某一类型的文件,诸如:
   b - 块设备文件
   d - 目录
   c - 字符设备文件
   l - 符号链接文件
   p - 管道文件
   f - 普通文件

-size n :[c] 查找文件长度为n块文件,带有c时表文件字节大小
-amin n   查找系统中最后N分钟访问的文件
-atime n  查找系统中最后n*24小时访问的文件
-cmin n   查找系统中最后N分钟被改变文件状态的文件
-ctime n  查找系统中最后n*24小时被改变文件状态的文件
-mmin n   查找系统中最后N分钟被改变文件数据的文件
-mtime n  查找系统中最后n*24小时被改变文件数据的文件
(用减号-来限定更改时间在距今n日以内的文件,而用加号+来限定更改时间在距今n日以前的文件。 )
-maxdepth n 最大查找目录深度
-prune 选项来指出需要忽略的目录。在使用-prune选项时要当心,因为如果你同时使用了-depth选项,那么-prune选项就会被find命令忽略
-newer 如果希望查找更改时间比某个文件新但比另一个文件旧的所有文件,可以使用-newer选项

Examples:

(1) Find files modified within 48 hours

find -atime -2

(2) Find files ending with .log in the current directory..Represents the current directory.

find ./ -name '*.log'

(3) Find files with permission 777 under 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 option is followed by a command, and its termination is marked by ;. Therefore, the semicolon after this command is essential. Considering that the semicolon may have different meanings in different systems, a backslash is added before it. The {} braces represent the file names found by the preceding find command.

Examples:

(5) Find files in the current directory whose modification time is more than 10 days old and delete them (without warning)

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

(6) Find all files in the current directory whose names end with .log and whose modification time is more than 5 days old, and delete them, but with a prompt before deletion. Press y to delete the file, press n to skip.

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

(7) Find files in the current directory whose file names start with passwd and whose content contains the characters "pkg"

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

(8) Use the exec option to execute the cp command

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

-xargs: The find command passes matched files to the xargs command, and the xargs command only takes a portion of the files at a time rather than all at once, unlike the -exec option. This way it can first process the first batch of files, then the next batch, and so on.

Examples:

(9) Find every regular file in the current directory, then use xargs to determine the file type

find . -type f -print | xargs file

(10) Find all regular files in the current directory that end with js and contain the characters 'editor'

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

(11) Use xargs to execute the mv command

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

(12) Use the grep command to search for the word hostnames in all regular files in the current directory and mark the lines where it appears:

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

(13) Find files in the current directory that start with a lowercase letter and end with a digit from 4 to 9 followed by .log:

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

(14) Find in the test directory but not in the test4 subdirectory

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

(15) Example 1: Find files whose modification time is newer than log2012.log but older than log2017.log

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

Using the depth option:

The depth option allows the find command, when backing up a file system to tape, to first back up all files, and then back up files in subdirectories.

Example: The find command starts from the root directory of the file system and searches for a file named CON.FILE. It will first match all files and then enter subdirectories to search.

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

18. chmod command

Used to change the access permissions of files or directories in a Linux system. It is used to control the access permissions of files or directories. This command has two modes of use. One is the symbolic mode, which contains letters and operator expressions; the other is the numeric mode, which contains numbers.

Each file or directory has three groups of access permissions, each represented by three bits: the read, write, and execute permissions of the file owner; the read, write, and execute permissions of users in the same group as the owner; and the read, write, and execute permissions of other users in the system. You can use ls -l test.txt to view them.

Take the file log2012.log as an example:

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

The first column has a total of 10 positions, and the first character specifies the file type. In a general sense, a directory is also a file. If the first character is a hyphen, it indicates a non-directory file. If it is d, it indicates a directory. From the second character to the tenth, there are 9 characters, grouped in threes, representing the permissions of the three groups of users on the file or directory. In the permission characters, a hyphen represents no permission, r represents read, w represents write, and x represents execute.

Common options:

-c 当发生改变时,报告处理信息
-R 处理指定目录以及其子目录下所有文件

Permission scope:

u :目录或者文件的当前的用户
g :目录或者文件的当前的群组
o :除了目录或者文件的当前用户或群组之外的用户或者群组
a :所有的用户及群组

Permission codes:

r :读权限,用数字4表示
w :写权限,用数字2表示
x :执行权限,用数字1表示
- :删除权限,用数字0表示
s :特殊权限

Examples:

(1) Add execute permission for all users to the file t.log

chmod a+x t.log

(2) Remove all original permissions, then give the owner read permission, and output processing information

chmod u=r t.log -c

(3) Assign the owner of file read, write, and execute (7) permissions; assign the file's group read and execute (5) permissions; assign other users execute (1) permission

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

(4) Add read permission to all files in the test directory and its subdirectories

chmod u+r,g+r,o+r -R text/ -c
19. The tar command

Used to compress and decompress files. tar itself does not have compression functionality; it only has packaging functionality. Compression and decompression are accomplished by invoking other functions.

Clarify two concepts: packaging and compression. Packaging refers to combining a large number of files or directories into a single total file; compression refers to turning a large file into a small file through some compression algorithm.

Common options:

-c 建立新的压缩文件
-f 指定压缩文件
-r 添加文件到已经压缩文件包中
-u 添加改了和现有的文件到压缩包中
-x 从压缩包中抽取文件
-t 显示压缩文件中的内容
-z 支持gzip压缩
-j 支持bzip2压缩
-Z 支持compress解压文件
-v 显示操作过程

About gzip and bzip2 compression:

gzip 实例:压缩 gzip fileName .tar.gz 和.tgz  解压:gunzip filename.gz 或 gzip -d filename.gz
          对应:tar zcvf filename.tar.gz     tar zxvf filename.tar.gz

bz2实例:压缩 bzip2 -z filename .tar.bz2 解压:bunzip filename.bz2或bzip -d filename.bz2
       对应:tar jcvf filename.tar.gz         解压:tar jxvf filename.tar.bz2

Examples:

(1) Package all files into a tar archive

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

(2) Package all files and directories under /etc into the specified directory and compress with gz

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

(3) View the contents of the just-packaged file (must add z because it is compressed with gzip)

tar -ztvf /tmp/etc.tar.gz

(4) Compress and package /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 a specified user or group. The user can be a username or user ID; the group can be a group name or group ID; the files are a space-separated list of files whose permissions are to be changed, and wildcards are supported.

-c 显示更改的部分的信息
-R 处理指定目录及子目录

Examples:

(1) Change the owner and group and display the change information

chown -c mail:mail log2012.log

(2) Change the file group

chown -c :mail t.log

(3) Change the owner and group of the folder and its subdirectories to mail

chown -cR mail: test/

21. df command

Displays disk space usage. It obtains information such as how much space has been used on the hard disk and how much space remains. 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 units of 1KB, unless the environment variable POSIXLY_CORRECT is specified, in which case it will be displayed in units of 512 bytes:

-a 全部文件系统列表
-h 以方便阅读的方式显示信息
-i 显示inode信息
-k 区块为1024字节
-l 只显示本地磁盘
-T 列出文件系统类型

Examples:

(1) Display disk usage

df -l

(2) List all file systems and their types in a human-readable way

df -haT

22. du command

The du command also checks disk usage, but unlike the df command, the Linux du command is used to view the disk space used by files and directories:

Command format:

du [选项] [文件]

Common options:

-a 显示目录中所有文件大小
-k 以KB为单位显示文件大小
-m 以MB为单位显示文件大小
-g 以GB为单位显示文件大小
-h 以易读方式显示文件大小
-s 仅显示总计
-c或--total  除了显示个别目录或文件的大小外,同时也显示所有目录或文件的总和

Examples:

(1) Display the size of the folder and subfolders in a human-readable way

du -h scf/

(2) Display the size of all files in the folder in a human-readable way

du -ah scf/

(3) Display the disk space occupied by each of several files or directories, and also calculate 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

Function is to create a synchronous link for a file at another location. When different directories need the same file, there is no need to create the same file for each directory; the link created via ln reduces disk usage.

Link categories: symbolic links and hard links.

Symbolic link:

  • 1. A symbolic link exists in the form of a path. Similar to shortcuts in the Windows operating system.
  • 2. Symbolic links can cross file systems; hard links cannot.
  • 3. A symbolic link can be linked to a nonexistent file name.
  • 4. Symbolic links can link to directories.

Hard link:

  • 1. A hard link exists in the form of a file copy, but does not occupy actual space.
  • 2. Creating hard links to directories is not allowed.
  • 3. Hard links can only be created within the same file system.

Notes:

  • First: The ln command keeps all linked files synchronized; that is, no matter which one you modify, the other files will undergo the same changes.
  • Second: ln links are divided into symbolic links and hard links. A symbolic link is "ln -s source_file target_file"; it only creates a mirror of the file at the location you choose and does not occupy disk space. A hard link is "ln source_file target_file" without the -s parameter; it creates a file at the chosen location with the same size as the source file. Whether symbolic or hard, the files remain synchronized.
  • Third: The ln command is used to link files or directories. If two or more files or directories are specified at the same time and the final destination is an existing directory, all the previously specified files or directories will be copied into that directory. If multiple files or directories are specified at the same time but the final destination is not an existing directory, an error message will appear.

Common parameters:

-b 删除,覆盖以前建立的链接
-s 软链接(符号链接)
-v 显示详细处理过程

Examples:

(1) Create a symbolic link for a file and display operation information.

ln -sv source.log link.log

(2) Create a hard link for a file and display operation information.

ln -v source.log link1.log

(3) Create a symbolic link for a directory.

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

24. date command

Display or set the system date and time.

Command parameters:

-d<字符串>  显示字符串所指的日期与时间。字符串前后必须加上双引号。
-s<字符串>  根据字符串来设置日期与时间。字符串前后必须加上双引号。
-u  显示GMT。
%H 小时(00-23)
%I 小时(00-12)
%M 分钟(以00-59来表示)
%s 总秒数。起算时间为1970-01-01 00:00:00 UTC。
%S 秒(以本地的惯用法来表示)
%a 星期的缩写。
%A 星期的完整名称。
%d 日期(以01-31来表示)。
%D 日期(含年月日)。
%m 月份(以01-12来表示)。
%y 年份(以00-99来表示)。
%Y 年份(以四位数来表示)。

Examples:

(1) Display the next day.

date +%Y%m%d --date="+1 day"  //显示下一天的日期

(2) Use of the -d parameter.

date -d "nov 22"  今年的 11 月 22 日是星期三
date -d '2 weeks' 2周后的日期
date -d 'next monday' (下周一的日期)
date -d next-day +%Y%m%d(明天的日期)或者:date -d tomorrow +%Y%m%d
date -d last-day +%Y%m%d(昨天的日期) 或者:date -d yesterday +%Y%m%d
date -d last-month +%Y%m(上个月是几月)
date -d next-month +%Y%m(下个月是几月)

25. cal command

Can display the Gregorian calendar for the user. 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 显示前一月,当前月,后一月三个月的日历
-m 显示星期一为第一列
-j 显示在当前年第几天
-y [year]显示当前年[year]份的日历

Examples:

(1) Display the date for a specified year and month.

cal 9 2012

(2) Display the calendar for each month of 2013.

cal -y 2013

(3) Set Monday as the first column, display the previous, current, and next three months.

cal -3m

26. grep command

A powerful text search command. grep (Global Regular Expression Print) is a global regular expression search.

grep works like this: it searches for a string template in one or more files. If the template contains spaces, it must be quoted. All strings after the template are treated as file names. The search results are sent to standard output and do not affect the original file contents.

Command format:

grep [option] pattern file|dir

Common parameters:

-A n --after-context显示匹配字符后n行
-B n --before-context显示匹配字符前n行
-C n --context 显示匹配字符前后n行
-c --count 计算符合样式的列数
-i 忽略大小写
-l 只列出文件内容符合指定的样式的文件名称
-f 从文件中读取关键词
-n 显示匹配内容的所在文件中行数
-R 递归查找文件夹

grep regular expression rules:

^  #锚定行的开始 如:'^grep'匹配所有以grep开头的行。 
$  #锚定行的结束 如:'grep$'匹配所有以grep结尾的行。 
.  #匹配一个非换行符的字符 如:'gr.p'匹配gr后接一个任意字符,然后是p。  
*  #匹配零个或多个先前字符 如:'*grep'匹配所有一个或多个空格后紧跟grep的行。
.*   #一起用代表任意字符。  
[]   #匹配一个指定范围内的字符,如'[Gg]rep'匹配Grep和grep。 
[^]  #匹配一个不在指定范围内的字符,如:'[^A-FH-Z]rep'匹配不包含A-R和T-Z的一个字母开头,紧跟rep的行。  
\(..\)  #标记匹配字符,如'\(love\)',love被标记为1。   
\<      #锚定单词的开始,如:'\<grep'匹配包含以grep开头的单词的行。
\>      #锚定单词的结束,如'grep\>'匹配包含以grep结尾的单词的行。
x\{m\}  #重复字符x,m次,如:'0\{5\}'匹配包含5个o的行。 
x\{m,\}  #重复字符x,至少m次,如:'o\{5,\}'匹配至少有5个o的行。  
x\{m,n\}  #重复字符x,至少m次,不多于n次,如:'o\{5,10\}'匹配5--10个o的行。  
\w    #匹配文字和数字字符,也就是[A-Za-z0-9],如:'G\w*p'匹配以G后跟零个或多个文字或数字字符,然后是p。  
\W    #\w的反置形式,匹配一个或多个非单词字符,如点号句号等。  
\b    #单词锁定符,如: '\bgrep\b'只匹配grep。

Examples:

(1) Find a specified process.

ps -ef | grep svn

(2) Find the number of specified processes.

ps -ef | grep svn -c

(3) Read keywords from a file.

cat test1.txt | grep -f key.log

(4) Recursively search for lines starting with grep in a folder, and list only the files.

grep -lR '^grep' /tmp

(5) Find lines that do not start with x.

grep '^[^x]' test.txt

(6) Display content lines containing "ed" or "at" characters.

grep -E 'ed|at' test.txt

27. wc command

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

Command format:

wc [option] file..

Command parameters:

-c 统计字节数
-l 统计行数
-m 统计字符数
-w 统计词数,一个字被定义为由空白、跳格或换行字符分隔的字符串

Examples:

(1) Find the file's line count, word count, byte count, and file name.

wc text.txt

Result:

7     8     70     test.txt

(2) Count the number of lines in the output result.

cat test.txt | wc -l

28. ps command

ps (process status) is used to view the status of currently running processes, as a one-time view. If you need dynamic continuous results, use top.

On Linux, processes have 5 states:

  • 1. Running (running or waiting in the run queue)
  • 2. Interruptible (sleeping, blocked, waiting for a condition to be met or a signal to be received)
  • 3. Uninterruptible (does not wake up or run upon receiving a signal; the process must wait until an interrupt occurs)
  • 4. Zombie (the process has terminated, but the process descriptor still exists until the parent process calls the wait4() system call to release it)
  • 5. Stopped (the process stops running after receiving SIGSTOP, SIGSTP, SIGTIN, or SIGTOU signals)

ps tool identifies 5 process state codes:

D 不可中断 uninterruptible sleep (usually IO)
R 运行 runnable (on run queue)
S 中断 sleeping
T 停止 traced or stopped
Z 僵死 a defunct (”zombie”) process

Command parameters:

-A 显示所有进程
a 显示所有进程
-a 显示同一终端下所有进程
c 显示进程真实名称
e 显示环境变量
f 显示进程间的关系
r 显示当前终端运行的进程
-aux 显示所有包含其它使用的进程

Examples:

(1) Display all current process environment variables and inter-process relationships.

ps -ef

(2) Display all current processes.

ps -A

(3) Combine with grep to find a process.

ps -aux | grep apache

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

ps aux | grep '(cron|syslog)'

29. top command

Display information about processes currently executing on the system, including process ID, memory usage, CPU usage, etc.

Common parameters:

-c 显示完整的进程命令
-s 保密模式
-p <进程号> 指定进程显示
-n <次数>循环显示次数

Examples:

(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.

First line: task queue information, same as the execution result of the uptime command. Specific parameter descriptions are 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 (and it hasn't been rebooted during this period!).

2 users — there are currently 2 users logged into the system.

load average: 1.15, 1.42, 1.44 — the three numbers after load average are the load conditions for 1 minute, 5 minutes, and 15 minutes respectively.

The load average data checks the number of active processes every 5 seconds, then calculates a value using a specific algorithm. If this number divided by the number of logical CPUs exceeds 5, it indicates that the system is overloaded.

Second line: Tasks — tasks (processes). Specific information is as follows:

The system currently has 206 processes in total, of which 1 is running, 205 are sleeping, 0 are in stopped state, and 0 are in zombie state.

Third line: CPU status information. Specific attribute descriptions are as follows:

5.9%us — 用户空间占用CPU的百分比。
3.4% sy — 内核空间占用CPU的百分比。
0.0% ni — 改变过优先级的进程占用CPU的百分比
90.4% id — 空闲CPU百分比
0.0% wa — IO等待占用CPU的百分比
0.0% hi — 硬中断(Hardware IRQ)占用CPU的百分比
0.2% si — 软中断(Software Interrupts)占用CPU的百分比

Note:Here the CPU usage ratio concept is different from Windows. You need to understand the relevant knowledge of Linux user space and kernel space!

Fourth line: memory status. Specific information is as follows:

32949016k total — 物理内存总量(32GB)
14411180k used — 使用中的内存总量(14GB)
18537836k free — 空闲内存总量(18GB)
169884k buffers — 缓存的内存量 (169M)

Fifth line: swap partition information. Specific information is as follows:

32764556k total — 交换区总量(32GB)
0k used — 使用的交换区总量(0K)
32764556k free — 空闲交换区总量(32GB)
3612636k cached — 缓冲的交换区总量(3.6GB)

Sixth line: blank line.

Seventh line and below: status monitoring of each process (task). Project column information descriptions are as follows:

PID — 进程id
USER — 进程所有者
PR — 进程优先级
NI — nice值。负值表示高优先级,正值表示低优先级
VIRT — 进程使用的虚拟内存总量,单位kb。VIRT=SWAP+RES
RES — 进程使用的、未被换出的物理内存大小,单位kb。RES=CODE+DATA
SHR — 共享内存大小,单位kb
S — 进程状态。D=不可中断的睡眠状态 R=运行 S=睡眠 T=跟踪/停止 Z=僵尸进程
%CPU — 上次更新到现在的CPU时间占用百分比
%MEM — 进程使用的物理内存百分比
TIME+ — 进程使用的CPU时间总计,单位1/100秒
COMMAND — 进程名称(命令名/命令行)

top interactive commands

h 显示top交互命令帮助信息
c 切换显示命令名称和完整命令行
m 以内存使用率排序
P 根据CPU使用百分比大小进行排序
T 根据时间/累计时间进行排序
W 将当前设置写入~/.toprc文件中
o或者O 改变显示项目的顺序

30. kill command

Send the specified signal to the corresponding process. If no signal type is specified, SIGTERM (15) will be sent to terminate the specified process. If the program still cannot be terminated, use the "-KILL" parameter, which sends the signal SIGKILL (9) to force the process to end. Use the ps command or the jobs command to view the process number. The root user can affect any user's processes; non-root users can only affect their own processes.

Common parameters:

-l  信号,若果不加信号的编号参数,则使用“-l”参数会列出全部的信号名称
-a  当处理当前进程时,不限制命令名和进程号的对应关系
-p  指定kill 命令只打印相关进程的进程号,而不发送任何信号
-s  指定发送信号
-u  指定用户

Examples:

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

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

31. free command

Display system memory usage, including physical memory, swap memory, and kernel buffer memory.

Command parameters:

-b 以Byte显示内存使用情况
-k 以kb为单位显示内存使用情况
-m 以mb为单位显示内存使用情况
-g 以gb为单位显示内存使用情况
-s<间隔秒数> 持续显示内存
-t 显示内存使用总合

Examples:

(1) Display memory usage.

free
free -k
free -m

(2) Display memory usage information in total form.

free -t

(3) Periodically query memory usage.

free -s 10

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