Detailed explanation and usage of common Linux commands

coldplay.xixi
Release: 2020-09-12 11:34:02
Original
24240 people have browsed it

Detailed explanation and usage of common Linux commands: 1. The reboot command is used to restart the machine; 2. The ls command is used to view the files contained in the linux folder; 3. The cd switch command is used to switch the current directory to dirName; 4 , pwd command is used to view the current working directory path; 5. mkdir command is used to create folders, etc.

Related learning recommendations: linux video tutorial

Power on and off command

reboot命令用于重启机器
poweroff用于关闭系统
Copy after login

ifconfig View ip address

直接输入ifconfig会列出已经启动的网卡,也可以输入ifconfig eth0单独显示eth0的信息
各选项解释是:
eth0    网卡的代号 
lo        回环地址loopback
inet    IPv4的Ip地址
netmask    子网掩码
broadcast    广播地址
RX/TX     流量发/收情况     tx是发送(transport),rx是接收(receive)
packets     数据包数
errors     数据包错误数
dropped    数据包有问题被丢弃的数量
collisions    数据包碰撞情况,数值太多代表网络状况差
Copy after login

User related

  • Add user, settings Password

    #添加用户
    useradd oldboy 
    #设置密码       
    passwd redhat
    
    root用户可以修改其他所有人的密码,且不需要验证
    Copy after login
  • Switch user

    su命令可以切换用户身份的需求,
    su - username
    
    su命令中间的-号很重要,意味着完全切换到新的用户,即环境变量信息也变更为新用户的信息
    Copy after login
  • View current user

    #先看下当前用户(我是谁)
    whoami
    #切换用户
    su - oldboy
    #退出用户登录
    logout
    ctrl + d
    Copy after login

Permission related

  • View permissions

    ls -l /var/log/mysqld.log
    Copy after login

    r    read可读,可以用cat等命令查看
    w    write写入,可以编辑或者删除这个文件
    x    executable    可以执行
    Copy after login

Special character redirection related

输入/输出 重定向符号
1.>>    追加重定向,把文字追加到文件的结尾
2.>     重定向符号,清空原文件所有内容,然后把文字覆盖到文件末尾
3. /tmp/oldboy.txt
echo "chaoge666" >> /tmp/oldboy.txt
cat >>/tmp/oldboy.txt  /tmp/network.txt   #标准输出重定向 把命令执行结果信息,放入到文件中
3.通配符  
ls -l /etc/us*
Copy after login

iptables firewall

centos7默认已经使用firewall作为防火墙了
1.关闭防火墙
systemctl status firewalld #查看防火墙状态
systemctl stop firewalld    #关闭防火墙
systemctl disable firewalld#关闭防火墙开机启动
systemctl is-enabled firewalld.service#检查防火墙是否启动
Copy after login

1. The ls command

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

Commonly used parameter combinations:

ls -a lists the directory All files, including hidden files starting with .

ls -A List other files except . and ..

ls -r Sort in reverse order

ls -t Sort by file modification time

ls -S Sort by file size

ls -h Display by human-readable size

ls -l In addition to the file name, also List the permissions, owners, file size and other information in detail

Example:

(1) Sort in reverse chronological order in an easy-to-read manner and display the file details

ls -lhrt

(2) Display file details in reverse order by size

ls -lrS

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

ls -l t*

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

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

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

find $pwd -maxdepth 1 | xargs ls -ld

2. cd switch

(changeDirectory), command syntax: cd [directory name]. Description: Switch the current directory to dirName

Example:

(1) Enter the desired directory

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 View the current working directory path

View the current working directory path

Example:

(1) View the current path

pwd

(2) View the actual path of the soft link

pwd -P

4. mkdir creates a folder

Creates a folder

Available options:

-m: Set access permissions for the new directory, or use the chmod command to set it ;

-p: can be a path name. At this time, if some directories in the path do not yet exist, after adding this option, the system will automatically create those directories that do not yet exist, that is, multiple directories can be created at one time;

Example:

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

mkdir t

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

mkdir -p /tmp/test/t1/t

5. rm delete the file

Delete the file in a directory One or more files or directories. 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 [options] 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 do not need to confirm one by one

rm -rf test

(3) Delete files starting with -f

rm -- -f*

6, rmdir Delete empty directories

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

Note: Non-empty directories cannot be deleted

Example:

(1) When the parent subdirectory is deleted and it becomes an empty directory, it will be deleted as well.

rmdir -p parent/child/child11

7, mv move/modify file name

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

When the second parameter is a directory, multiple files can be separated by spaces as the first parameter, and multiple files can be moved to the directory specified by parameter 2

Example:

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

mv test.log test1.txt

(2) Rename the files log1.txt, log2.txt, log3 .txt is moved to the root test3 directory

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

(3) Rename file 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 upper level directory

mv * ../

8, cp Copy

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

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 will overwrite it directly!

-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 time. If the original file exists, you will be prompted whether to overwrite it

cp -ai a.txt test

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

cp -s a.txt link_a.txt

9, cat displays file details

Cat has three main functions:

1. Display the entire file at one time: cat filename

2. Create a file from the keyboard: cat > filename can only create new files and cannot edit existing files. .

3. Merge several files into one file: cat file1 file2 > file

-b outputs non-empty line numbers

-n outputs all line numbers

Example:

(1) Add the line number to the file content of log2012.log and enter it into the file log2013.log

cat -n log2012.log log2013.log

(2) Add line numbers to the file contents of log2012.log and log2013.log (blank lines are not added) and then append the contents to log.log

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

(3) Use here doc to generate a new file

cat >log.txt

>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 Paging display

The function is similar to cat. More will display page by page to facilitate users to read page by page. The most basic command is to press the space key (space) to display the next page, and press the b key to go back. (back) Display one page

->>Command parameters:

n Start displaying from the nth line

-n Define the screen size to be n lines

/pattern Search for the string (pattern) before each file is displayed, and then display it starting from the first two lines of the string

-c Clear the screen from the top, and then display

-d Prompt "Press space to continue, 'q' to quit (press space bar to continue, press q key to exit)", disable the ring function

-l Ignore Ctrl l (page change) character

-p Paging the file by clearing the window instead of scrolling, similar to the -c option

-s Displays multiple consecutive blank lines as one line

-u Remove the underline in the file content

->>Common operation command:

Enter Go down n lines and 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 the previous screen

= Output The line number of the current line

: f Output the file name and the line number of the current line

V Call the vi editor

! Command Call the Shell and execute the command

q Exit more

Example:

(1) Display the content from line 3 onwards in the file

more 3 text.txt

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

ls -l | more -5

Press the space to display the next 5 lines

11. The less command

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

Common command parameters

-i Ignore the case when searching

-N Display the line number of each line

-o

-s Display consecutive empty lines in one line

/String: Search downward for "string" function

?String: Function to search upward for "string"

n: Repeat the previous search (related to / or ?)

N: Repeat the previous search in reverse (related to / or ?)

-x Display the "tab" key as the specified number space

b Turn back one page

d Turn back half a page

h Display the help interface

Q Exit less command

u Scroll half a page forward

y Scroll forward one line

Space bar scrolls one line

Enter key scrolls one page

[pagedown]: Scroll down a page

[pageup]: Scroll up a page

Example:

(1) ps to view process information And display it through less paging

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. Head n lines of text from the beginning.

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.

Commonly used parameters:

-n The number of lines displayed (the number of lines is a plural number, counting from the end to the front)

Example:

(1) Display the first 20 lines in 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 The n lines of text from the end

are used to display the content at the end of the specified file. When no file is specified, it is processed as input information. Commonly used to view log files.

Commonly used parameters:

-f loop reading (often used to view incremental log files)

-n Display the number of lines (from back to front )

(1) Loop to read the gradually increasing file content

ping 127.0.0.1 > ping.log & (running in the background: you can use jobs -l to view, or you can use fg to Move it to the foreground to run)

tail -f ping.log (view log)

14. whichView the location of the executable file

at If you want to find a file in Linux but don't know where it is located, you can use the following commands to search:

which View the location of the executable file.

whereis View the location of the file.

locate Use the database to view the file location.

find Actually search the hard disk to query the file name.

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

Common parameters:

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

Example:

(1) Check whether the ls command exists and which

to execute which ls

(2) Check which

which which

(3) View cd

which cd (shows that it does not exist because cd is a built-in command, and which search shows that it is a command in PATH)

View Current PATH configuration: echo $PATH; or use env to view all environment variables and corresponding values

15. whereis View executable files

whereis command can only be used to search for program names, and only Search binary files (parameter -b), man documentation (parameter -m) and source code files (parameter -s). If parameters are omitted, all information is returned. Whereis and locate both search based on the system's built-in database, so they are very efficient, while find traverses the hard disk to find files.

Commonly used parameters:

-b Locate the executable file.

-m Locate help file.

-s Locate source code files.

-u Search for files other than executable files, source code files, and help files in the default path.

Example:

(1) Find files related to locate program

whereis locate

(2) Find source code files of locate

whereis -s locate

(3) Find the lcoate help file

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 called periodically by the cron daemon. By default, the locate command searches the database faster than searching the entire hard disk data. However, the disadvantage is that if the files found by locate are recently created or renamed, they may not be found. , updatedb will run once a day, and the setting value can be updated by modifying crontab. (etc/crontab).

locate is similar to the find command. You can use *, ?, etc. to perform regular matching searches.

Common parameters:

-l num (the number of lines to be displayed)

-f Exclude specific file systems, such as proc

-r Use regular expressions as search conditions

Example:

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

locate pwd

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

locate /etc/sh

(3) Search for files ending with reason in the /var directory

locate -r '^/var.reason$' (where . represents one character, represents multiple tasks ; .* represents any number of characters)

17. find Find files in the file tree

is used to find files in the file tree and handle them accordingly.

Command format:

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

Command parameters:

pathname: find command location Directory path to look for. For example, use . to represent the current directory and / to represent the system root directory.

-print: The find command outputs matching files to standard output.

-exec: The find command executes the shell command given by this parameter on the matching file. The corresponding command is in the form of 'command' { };, pay attention to the space between { } and \;.

-ok: It has the same function as -exec, except that it executes the shell command given by this parameter in a safer mode. Before executing each command, a prompt will be given to let The user determines whether to execute.

Command options:

-name Search files by file name

-perm Search files by file permissions

-user Search files by file owner

-group Find files according to the group to which they belong.

-type Find a file of a certain type, such as:

b - block device file

d - directory

c - character device file

l - Symbolic link file

p - Pipe file

f - Ordinary file

-size n: [c] Find files with a file length of n blocks, With c time table file byte size

-amin n Find the files accessed in the last N minutes in the system

-atime n Find the files accessed in the last n*24 hours in the system

-cmin n Find files whose file status has been changed in the last N minutes in the system

-ctime n Find files whose file status has been changed in the last n*24 hours in the system

-mmin n Find files with changed file data in the last N minutes in the system

-mtime n Find files with changed file data in the last n*24 hours in the system

(Use the minus sign - to limit the change time Files within n days from now, and use the plus sign to limit the change time of files before n days from now. )

-maxdepth n Maximum search directory depth

-prune option to Indicate directories to be ignored. Be careful when using the -prune option, because if you also use the -depth option, the -prune option will be ignored by the find command

-newer If you want to find a file that has a change time that is newer than another file For all old files in a file, you can use the -newer option

Example:

(1) Find files modified within 48 hours

find -atime -2

(2) Search for files ending with .log in the current directory. ". "Represents the current directory

find ./ -name '*.log'

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

find /opt -perm 777

(4) Find files larger than 1K

find -size 1000c

find -size 1000c Find files equal to 1000 characters

- The exec parameter is followed by the command command, and its termination is marked with;, so the semicolon after this command is indispensable. Considering that the semicolon has different meanings in various systems, add inverse in front of it. slash. {} The curly braces represent the file name found by the previous find.

Example:

(5) Find files in the current directory that have changed time before 10 days and delete them (no reminder)

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

(6) In the current directory, search for all files whose file names end with .log and whose modification time is more than 5 days, and delete them, but before deleting, give Prompt. Press the y key to delete the file, press the n key not to delete it

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

(7) Find files in the current directory Files whose names start with passwd and whose contents contain "pkg" characters

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

(8) Use the exec option Execute the cp command

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

-xargs The find command passes the matched file to the xargs command, and the xargs command each time Get only part of the file instead of all, unlike the -exec option. This way it can process the first batch of files it gets, then the next batch, and so on.

Example:

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

find . -type f -print | xargs file

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

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

find -type f -name '*.js' | xargs grep -lF 'editor'

(11) Use xargs to execute mv command

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

(12) Use 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 starting with a lowercase letter and ending with 4 to 9Add the file ending with .log

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

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

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

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

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

Use the depth option: The

depth option allows the find command to back up the file system on tape. It is hoped that all files will be backed up first, and then the sub-files will be backed up. files in the directory.

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 search in subdirectories

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

18, grep text search command

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

grep works like this, it searches for strings in one or more files template. If the template contains spaces, it must be quoted, and all strings following the template are treated as file names. The search results are sent to standard output without affecting the original file content.

Command format:

grep [option] pattern file|dir

Common parameters:

-A n --after-context displays after matching characters n lines

-B n --before-context Display n lines before the matching character

-C n --context Display n lines before and after the matching character

-c -- count Count the number of columns that match the style

-i Ignore case

-l List only the file names whose content matches the specified style

-f Read from the file Take the keyword

-n Display the number of lines in the file where the matching content is located

-R Recursively search the folder

grep’s regular expression:

^ #The start of an anchor line such as: '^grep' matches all lines starting with grep.

$ #End of anchor line For example: 'grep$' matches all lines ending with grep.

. #Match a non-newline character. For example: 'gr.p' matches gr followed by any character, then p.

* #Match zero or more previous characters. For example: '*grep' matches all lines with one or more spaces followed by grep.

.* #Used together to represent any character.

[] #Match a character 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 starting with a letter that does not contain A-R and T-Z, followed by rep.

(..) #Mark matching characters, such as '(love)', love is marked as 1.

> #Anchor the end of the word, such as 'grep>' matches lines containing words ending with grep.

x{m} #Repeat character x, m times, such as: '0{5}' matches lines containing 5 o's.

x{m,} #Repeat character x, at least m times, such as: 'o{5,}' matches lines 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 lines with 5--10 o's.

\w # Matches text and numeric characters, that is, [A-Za-z0-9], such as: 'G\w*p' matches G followed by zero or more text or numeric characters, Then there is p.

\W #The inverted form of \w, matches one or more non-word characters, such as period, period, etc.

\b #Word lock character, 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 the file

cat test1.txt | grep -f key.log

(4 ) Recursively search for lines starting with grep from the folder and list only the files

grep -lR '^grep' /tmp

(5) Find the contents of lines that are not x switches

grep '[x]' test.txt

(6) Display content lines containing ed or at characters

grep -E 'ed| at' test.txt

19, chmod Access permissions

is used to change the access permissions of Linux system files or directories. Use it to control access permissions to files or directories. This command has two uses. One is a text setting method that includes letters and operator expressions; the other is a numeric setting method that includes numbers.

Each file or directory has three groups of access permissions, each group is represented by three digits, which are the read, write and execute permissions of the file owner; the read, write and execution permissions of users in the same group as the owner. Execute permissions; read, write, and execute permissions for other users in the system. You can use ls -l test.txt to find

Take the file log2012.log as an example:

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

There are 10 positions in the first column, and the first character specifies the file type. In the usual sense, a directory is also a file. If the first character is a dash, it means it is a non-directory file. If it is d, it means a directory. There are a total of 9 characters starting from the second character to the tenth. A group of 3 characters represents the permissions of 3 groups of users on the file or directory. The permission characters use a horizontal line to represent empty permission, r represents read-only, w represents write, and x represents executable.

Commonly used parameters:

-c When changes occur, report processing information

-R Process all files in the specified directory and its subdirectories

Permissions Scope:

u: The current user of the directory or file

g: The current group of the directory or file

o: Except the current user or group of the directory or file Users or groups outside the group

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 Permissions

Example:

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

chmod a x t.log

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

chmod u=r t.log -c

(3) Assign read, write, Execute (7) permissions, assign read and execute (5) permissions to the file's group, and assign execution (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

20. tar compression and decompression

is used to compress and decompress files. tar itself does not have a compression function, only a packaging function. Compression and decompression are accomplished by calling other functions.

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

Common parameters:

- c Create a new compressed file

-f Specify the compressed file

-r Add files to the already compressed file package

-u Add modified and existing files to In the compressed package

-x Extract files from the compressed package

-t Display the contents of the compressed file

-z Support gzip compression

-j Support bzip2 compression

-Z Support compress decompression file

-v Display operation process

About gzip and bzip2 compression

gzip example: Compress 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 example: Compress bzip2 -z filename .tar.bz2 Decompress: bunzip filename.bz2 or bzip -d filename.bz2

Corresponding to: tar jcvf filename.tar.gz Decompression: tar jxvf filename.tar.bz2

Example:

(1) Pack all files into tar package

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

(2) Pack all files and directories under /etc into the specified directory and use gz compression

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

(3 ) View the contents of the file just packaged (be sure to add z, because it is compressed using gzip)

tar -ztvf /tmp/etc.tar.gz

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

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

21, chown Change For the specified user or group

chown changes the owner of the specified file to the specified user or group. The user can be the user name or user ID; the group can be the group name or group ID; the file is A space-separated list of files whose permissions need to be changed, wildcards are supported

-c Displays the information of the changed part

-R Processes the specified directory and subdirectory

Example:

(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 sub-file directory to mail

chown -cR mail: test/

(4) Change files

22, df Display disk space

Display disk space usage. Get information such as how much space is occupied on the hard disk, how much space is currently left, etc. If no file name is specified, the available space of all currently mounted file systems will be displayed. By default, disk space will be 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 List of all file systems

- h Display information in an easy-to-read manner

-i Display inode information

-k Block size is 1024 bytes

-l Display only local disk

-T List file system types

Example:

(1) Display disk usage

df -l

(2) Easy to read Ways to list all file systems and their types

df -haT

23. du Check the space used

The du command also checks the space used, but unlike the df command, the Linux du command checks the space used by files and directory disks.

Command format:

du [options][file]

Common parameters:

-a Display the size of all files in the directory

-k Display the file size in KB units

-m Display the file size in MB units

-g Display the file size in GB units

-h Yiyi Display file size in read mode

-s Display only the total

-c or --total In addition to displaying the size of individual directories or files, it also displays the total of all directories or files

Example:

(1) Display the size of the folder and subfolders in an easy-to-read manner

du -h scf/

(2) In an easy-to-read manner Method to display the size of all files in the folder

du -ah scf/

(3) Display the size of the disk space occupied by several files or directories, and also count their sum

du -hc test/ scf/

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

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

24. The function of the ln command

is to establish a synchronized link for the file in another location. When this problem is needed in different directories, there is no need to create a link for each directory. For the same file, the disk usage is reduced through the link created by ln.

Link classification: software link and hard link

Soft link:

1. Soft link exists in the form of a path. Similar to shortcuts in the Windows operating system

2. Soft links can cross file systems, but hard links cannot

3. Soft links can link to a non-existent file name

4. Soft links can link directories

Hard links:

1. Hard links exist in the form of file copies. But it doesn't take up actual space.

2. It is not allowed to create hard links to directories

3. Hard links can only be created in the same file system

Note:

One: The ln command will maintain the synchronization of each linked file, that is to say, no matter where you change, other files will have the same changes;

Second: The ln link is divided into There are two types of soft links and hard links. A soft link is ln -s source file target file. It will only generate a mirror image of a file at the location you select and will not occupy disk space. A hard link ln source file target file has no Parameter -s, it will generate a file with the same size as the source file at the location you selected. Whether it is a soft link or a hard link, the file will keep changing synchronously.

Third: The ln command is used to link files or directories. If more than two files or directories are specified at the same time, and the final destination is an existing directory, all previously specified files or directories will be Directory is copied into this directory. If multiple files or directories are specified at the same time, and the final destination is not an existing directory, an error message will appear.

Commonly used parameters:

-b Delete, overwrite the previously established link

-s Soft link (symbolic link)

-v Show detailed processing process

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 a soft link to the directory

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

25, date Display time

Display or set the system date and time

Command parameters:

-d Display the date and time pointed to by the string. The string must be preceded and followed by double quotes.

-s Set date and time based on string. The string must be preceded and followed by double quotes.

-u Display GMT.

%H hours (00-23)

%I hours (00-12)

%M minutes (expressed as 00-59)

%s Total seconds. The starting time is 1970-01-01 00:00:00 UTC.

%S Seconds (expressed in local usage)

%a Abbreviation of week.

%A The full name of the week.

%d Date (expressed as 01-31).

%D Date (including year, month and day).

%m month (represented by 01-12).

%y Year (expressed as 00-99).

%Y Year (expressed as four digits).

Example:

(1) Display the next day

date %Y%m%d --date=" 1 day" //Display the next day's date

(2) Use the -d parameter

date -d "nov 22" November 22 this year is Wednesday

date -d '2 weeks' the date 2 weeks later

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 is the last month)

date -d next-month %Y%m (what month is the next month)

26, cal command

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

Commonly used parameters:

-3 Display the calendar of the previous month, current month, and next month and three months

-m Display Monday as the first column

-j Display the day of the current year

-y [year] Display the calendar of the current year [year]

Example:

(1) Display the specified year Month date

cal 9 2012

(2) Display the calendar for each month of 2013

cal -y 2013

(3) Do it on Monday is the first column, showing the first, middle and last three months

cal -3m

27. The wc command

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

Command format:

wc [option] file..

Command parameters:

-c Count the number of bytes

-l Count the number of lines

-m Count the number of characters

-w Count the number of words, a word is defined as A string separated by blanks, tabs or newline characters

Example:

(1) Find the number of lines of the file, the number of words, the number of bytes, the file name

wc text.txt Result: 7 8 70 test.txt

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

cat test.txt | wc -l

28, ps View Process

ps(process status) is used to view the status of the currently running process. View it all at once. If you need dynamic and continuous results, use top

There are 5 states of processes on Linux:

\1. Running (running or waiting in the run queue)

\2. Interrupt (sleeping, blocked, waiting for a certain condition to form or receiving a signal)

\3. Uninterruptible (no wake-up and non-executable upon receiving a signal, the process must wait until an interrupt occurs)

\4. Zombie (the process has been terminated, but the process descriptor exists until the parent The process calls wait4() system call and is released)

\5. Stop (the process stops running after receiving SIGSTOP, SIGSTP, SIGTIN, SIGTOU signals)

5 types of ps tools to identify processes Status code:

D uninterruptible sleep (usually IO)

R runnable (on run queue)

S ​​interrupt sleeping

T stop traced or stopped

Z Zombie a defunct ("zombie") process

Command parameters:

-A Display all processes

a Display all processes

-a Display all processes under the same terminal

c Display the real name of the process

e Display environment variables

f Display the relationship between processes

r Display the processes running in the current terminal

-aux Display all processes including other uses

Example:

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

ps -ef

(2) Display all current processes

ps -A

(3) Use with grep to find a certain process

ps -aux | grep apache

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

ps aux | grep '(cron|syslog)'

29. top Executing process

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

Commonly used parameters:

-c Display the complete process command

-s Confidential mode

-p Display the specified process

-n Loop 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 situation.

The first line is the task queue information, which is the same as the execution result of the uptime command. The specific parameter description is 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 logging in to the system

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

Load average data is a value calculated by checking the number of active processes every 5 seconds and then calculating it according to a specific algorithm. If this number is divided by the number of logical CPUs, a result higher than 5 indicates that the system is overloaded.

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

The system now has a total of 206 processes, of which 1 is running and 205 are sleeping (sleep) ), 0 in stopped state, and 0 in zombie state (zombie).

The third line, cpu status information, the specific attribute description is as follows:

5.9%us - the percentage of CPU occupied by user space.

3.4% sy — The percentage of CPU occupied by kernel space.

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的百分比

备注:在这里CPU的使用比率和windows概念不同,需要理解linux系统用户空间和内核空间的相关知识!

第四行,内存状态,具体信息如下:

32949016k total — 物理内存总量(32GB)

14411180k used — 使用中的内存总量(14GB)

18537836k free — 空闲内存总量(18GB)

169884k buffers — 缓存的内存量 (169M)

第五行,swap交换分区信息,具体信息说明如下:

32764556k total — 交换区总量(32GB)

0k used — 使用的交换区总量(0K)

32764556k free — 空闲交换区总量(32GB)

3612636k cached — 缓冲的交换区总量(3.6GB)

第六行,空行。

第七行以下:各进程(任务)的状态监控,项目列信息说明如下:

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交互命令

h 显示top交互命令帮助信息

c 切换显示命令名称和完整命令行

m 以内存使用率排序

P 根据CPU使用百分比大小进行排序

T 根据时间/累计时间进行排序

W 将当前设置写入~/.toprc文件中

o或者O 改变显示项目的顺序

30、kill 杀死进程

发送指定的信号到相应进程。不指定型号将发送SIGTERM(15)终止指定进程。如果任无法终止该程序可用“-KILL” 参数,其发送的信号为SIGKILL(9) ,将强制结束进程,使用ps命令或者jobs 命令可以查看进程号。root用户将影响用户的进程,非root用户只能影响自己的进程。

常用参数:

-l  信号,若果不加信号的编号参数,则使用“-l”参数会列出全部的信号名称

-a  当处理当前进程时,不限制命令名和进程号的对应关系

-p  指定kill 命令只打印相关进程的进程号,而不发送任何信号

-s  指定发送信号

-u  指定用户

实例:

(1)先使用ps查找进程pro1,然后用kill杀掉

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

31、free 显示内存使用情况

显示系统内存使用情况,包括物理内存、交互区内存(swap)和内核缓冲区内存。

命令参数:

-b 以Byte显示内存使用情况

-k 以kb为单位显示内存使用情况

-m 以mb为单位显示内存使用情况

-g 以gb为单位显示内存使用情况

-s 持续显示内存

-t 显示内存使用总合

实例:

(1)显示内存使用情况

free

free -k

free -m

(2)以总和的形式显示内存的使用信息

free -t

(3)周期性查询内存使用情况

free -s 10

32、scp 传输文件

    scp是 secure copy的缩写, scp是linux系统下基于ssh登陆进行安全的远程文件拷贝命令

  • 语法
scp 【可选参数】 本地源文件 远程文件标记
Copy after login
  • 参数

    -r :递归复制整个目录
    -v:详细方式输出
    -q:不显示传输进度条
    -C:允许压缩
    Copy after login
  • 实例

    #传输本地文件到远程地址
    scp 本地文件  远程用户名@远程ip:远程文件夹/
    scp 本地文件  远程用户名@远程ip:远程文件夹/远程文件名
    
    scp /tmp/chaoge.py root@192.168.1.155:/home/
    scp /tmp/chaoge.py root@192.168.1.155:/home/chaoge_python.py
    
    scp -r  本地文件夹  远程用户名@远程ip:远程文件夹/
    scp -r /tmp/oldboy root@192.168.1.155:/home/oldboy
    
    #复制远程文件到本地
    scp root@192.168.1.155:/home/oldboy.txt /tmp/oldboy.txt
    scp -r root@192.168.1.155:/home/oldboy /home/
    Copy after login

33、VI 和vim   编辑文本

vi filename :打开或新建文件,并将光标置于第一行首

vi n filename :打开文件,并将光标置于第n行首

vi filename :打开文件,并将光标置于一行首

vi /pattern filename:打开文件,并将光标置于第一个与pattern匹配的串处

vi -r filename :在上次正用vi编辑时发生系统崩溃,恢复filename

vi filename....filename :打开多个文件,依次进行编辑

屏幕翻滚类命令

Ctrl u:向文件首翻半屏

Ctrl d:向文件尾翻半屏

Ctrl f:向文件尾翻一屏

Ctrl+b;向文件首翻一屏

nz:将第n行滚至屏幕顶部,不指定n时将当前行滚至屏幕顶部.

插入文本类命令

i :在光标前

I :在当前行首

a:光标后

A:在当前行尾

o:在当前行之下新开一行

O:在当前行之上新开一行

r:替换当前字符

R:替换当前字符及其后的字符,直至按ESC键

s:从当前光标位置处开始,以输入的文本替代指定数目的字符

保存命令

按ESC键 跳到命令模式,然后:

:w   保存文件但不退出vi

:w file 将修改另外保存到file中,不退出vi

:w!   强制保存,不推出vi

:wq  保存文件并退出vi

:wq! 强制保存文件,并退出vi

:q  不保存文件,退出vi

:q! 不保存文件,强制退出vi

:e! 放弃所有修改,从上次保存文件开始再编辑

之后,回车,ok!

详情博客:https://www.cnblogs.com/pyyu/p/9460649.html

常见环境变量变量

1、PATH

  • 注意事项: PATH中的环境变量有顺序,如果你添加的变量需要优先被搜索出,需要添加在变量首,否则放在尾部

  • 指定的命令搜索路径

  • 查看PATH

    echo $PATH
    Copy after login
  • 1 临时修改PATH变量

    export PATH=/usr/local/mongdb/bin:$PATH   # 将mongdb下的bin目录放在临时放在PATH变量中,以:号进行分割,
    Copy after login

    修改后通过echo $PATH查看配置

    优点:立即生效,

    缺点:临时改变,只针对当前终端,退出就恢复原样

  • 2 针对用户修改PATH变量

    vim ~/.bashrc 
    #在最后一行添加
    export PATH=/usr/local/mongodb/bin:$PATH
    
    #保存关闭
    #读取该文件让其生效
    source ~/.bashrc
    Copy after login

    优点:针对当前用户,永久有效

    缺点:仅限当前用户

  • 3 全局修改PATH变量

    # 编辑该文件
    vim /etc/profile
    
    # 在文件尾添加,
    export PATH=/usr/local/mongodb/bin:$PATH
    
    # 保存退出,重启生效
    Copy after login

    优点:针对所有用户

2、PS1 设置命令提示符显示的内容

  • 查看

    echo $PS1
    Copy after login
  • 内部变量

    \d  日期
    \H  完整主机名
    \h  主机名第一个名字
    \t  时间24小时制HHMMSS
    \T  时间12小时制
    \A  时间24小时制HHMM
    \u  当前用户账号名
    \v  BASH的版本
    \w  完整工作目录
    \W  利用basename取得工作目录名
    \#  下达的第几个命令
    \$  提示字符,root为#,普通用户为$
    Copy after login
  • 全局修改

    vim /etc/profile 
    
    # 尾添加
    PS1='[\u@\h \W\t]\$'    # 针对上述变量自行更改
    Copy after login

    注意重启

  • 临时修改

    export PS1='[\u@\h \W\t]\$'
    Copy after login

管道命令

命令格式: 命令A | 命令B

Linux提供的管道符“|”讲两条命令隔开,管道符左边命令的输出会作为管道符右边命令的输入。
常见用法:
#检查python程序是否启动
ps -ef|grep "python"

#找到/tmp目录下所有txt文件
ls /tmp|grep '.txt'

#检查nginx的端口是否存活
netstat -tunlp |grep nginx
Copy after login

alias 起别名命令

Linux如何提示你,在使用这些命令时候,提醒你小心呢?
#查看系统别名
alias
默认别名
alias cp='cp -i'
alias egrep='egrep --color=auto'
alias fgrep='fgrep --color=auto'
alias grep='grep --color=auto'
alias l.='ls -d .* --color=auto'
alias ll='ls -l --color=auto'
alias ls='ls --color=auto'
alias mv='mv -i'
alias rm='rm -i'
alias which='alias | /usr/bin/which --tty-only --read-alias --show-dot --show-tilde'

别名作用是:

我们在linux中使用cp时候相当于执行了cp -i
-i:删除已有文件或目录之前先询问用户;

#别名用比较危险的操作,防止你犯错
Copy after login

实例  为rm设置别名

#让系统显示 do not use rm
echo do not use rm
#设置rm别名
alias rm='echo do not use rm'
#设置别名永久生效,写入到/etc/profile(针对登录用户的合同,设置环境变量)
vim /etc/profile #编辑文件
G  快速到达最后一行
o  当前行下一行,创建一个新行,进入编辑模式
source /etc/profile #读取文件(合同生效)
---------------
#取消别名
unalias rm
Copy after login

想了解更多编程学习,敬请关注php培训栏目!

The above is the detailed content of Detailed explanation and usage of common Linux commands. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template