1、ls command is an abbreviation for list. The ls command can be used not only to view the files contained in a linux directory but also to check file permissions (including directory, folder, and file permissions) and to view directory information, etc.
Common parameter combinations:
ls -a lists all files in the directory, including hidden files that start with ..
ls -A lists all files except for . and ...
ls -r reverses the order of the listing
ls -t sorts files by modification time
ls -S sorts files by size ls -h displays sizes in a human-readable format ls -l provides detailed information about files, including permissions, owner, size, etc., in addition to the file name.
Examples:
(1) Sort by time in a human-readable format in reverse order and display detailed file information: ls -lhrt
(2) Display detailed file information sorted by size in reverse order: ls -lrS
(3) List all directories in the current directory that start with “t” with detailed content: ls -l t*
(4) List absolute paths of files (excluding 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 (change Directory), command syntax: cd [directory name]. Description: Switch the current directory to dirName
Examples:
(1) Enter the desired directory: cd /
(2) Enter the “home” directory: cd ~
(3) Enter the previous working path: cd –
(4) Use the parameter of the previous command as the parameter for cd: cd !$
3、pwd command 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 to create a folder. Available options: -m: set access permissions for the newly created directory, which can also be set using the chmod command; -p: can be a path name. If some directories in the path do not exist, this option will automatically create those directories that do not exist, allowing multiple directories to 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, creating it if it does not exist: mkdir -p /tmp/test/t1/t
5、rm command to delete one or more files or directories in a directory. If the -r option is not used, rm will not delete directories. If using rm to delete files, they can usually be restored: rm [options] files…
Examples:
(1) Delete any .log files; prompt for confirmation before deleting each: rm -i *.log
(2) Delete the test subdirectory and all files within it without confirmation: rm -rf test
(3) Delete files starting with -f: rm — -f*
6、rmdir command to remove one or more subdirectory entries from a directory. To delete a directory, you must also have write permission on its parent directory. Note: You cannot delete a non-empty directory.
Examples:
(1) If the parent subdirectory is deleted, making it an empty directory, delete it as well: rmdir -p parent/child/child11
7、mv command to move files or rename files. Depending on the type of the second parameter (if it is a directory, then move the file; if it is a file, then rename the file).
When the second parameter is a directory, multiple files can be specified as the first parameter, separated by spaces, to move multiple files to the specified directory.
Examples:
(1) Rename the file test.log to test1.txt: mv test.log test1.txt
(2) Move files log1.txt, log2.txt, log3.txt to the root directory test3: mv log1.txt log2.txt log3.txt /test3
(3) Rename the file file1 to file2, if file2 already exists, prompt 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
to copy source files to target files, or to copy multiple source files to target directories.
Note: When copying via command line, if the target file already exists, it will prompt whether to overwrite. However, in shell scripts, if the -i parameter is not added, it will not prompt and will directly overwrite! -i prompts -r to copy directories and all items within them -a to copy files with the same timestamp as the original files
Examples:
(1) Copy a.txt to the test directory, keeping 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 has three main functions:
1. Display the entire file at once: cat filename
2. Create a file from the keyboard: cat > filename can only create new files, cannot edit existing files.
3. Merge several files into one file: cat file1 file2 > file-b to output non-empty lines with line numbers: -n to output all line numbers
Examples:
(1) Add line numbers to the contents of log2012.log and input it into log2013.log: cat -n log2012.log log2013.log
(2) Add line numbers (excluding blank lines) to the contents of log2012.log and log2013.log and append the content to 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 HelloWorld PWD=/opt/soft/test
(4) Reverse the order of lines: tac log.txt PWD=/opt/soft/test World Hello
10、more command functions similarly to cat, more displays one page at a time for easier reading, with the basic command being to press the space bar (space) to display the next page, and the b key to go back (back) one page.
->> command parameters: +n display from the n line -n define the screen size as n lines +/pattern search for the string in each file before displaying, then start displaying from two lines before that string -c clear the screen from the top and then display -d prompt “Press space to continue, ‘q’ to quit” (press space to continue, press q to quit), disabling the bell function -l ignore Ctrl+l(page) characters
-p page through the file by clearing the window instead of scrolling, similar to the -c option -s display multiple consecutive blank lines as one line -u remove underlines from the file content
->> common operation commands: Enter move down n lines, needs to be defined. 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 current line number :f output the file name and current line number V call the vi editor! command call the Shell, and execute the command q exit more
Examples:
(1) Display content from the 3 line of the file: more +3 text.txt
(2) Display detailed information of the listed files, using a pipe to display 5 lines at a time: ls -l | more -5 press space to display the next 5 lines
11、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< number of lines to display (if the number is plural, it counts from the end)
Examples:
(1) Display the first 20 lines of the file 1.log: head 1.log -n 20
(2) Display the first 20 bytes of the file 1.log: head -c 20 log2014.log
(3) Display the last 10 lines of the file t.log: head -n -10 t.log
12、tail command is used to display the content at the end of a specified file. If no file is specified, it processes input information. Commonly used to view log files.
Common parameters: -f loop read (commonly used to view incrementing log files) -n< number of lines to display (counting from the end)
(1) Loop read gradually increasing file content: ping 127.0.0.1 > ping.log & (run in the background: you can use jobs -l to view, and you can use fg to bring it to the foreground) tail -f ping.log (view log)
13、chmod command is used to change the access permissions of files or directories in the linux system. It controls the access permissions of files or directories. This command has two usages: one is the literal setting method that includes letters and operator expressions; the other is the numeric setting method that includes numbers.
Each file or directory’s access permissions have three groups, 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 find for example, for the file log2012.log: -rw-r–r– 1 root root 296K 11-13 06:03 log2012.log The first column has a total of 10 positions, the first character indicates the file type. In general, a directory is also a file. If the first character is a dash, it indicates a non-directory file. If it is d, it indicates a directory. From the second character to the tenth, there are a total of 9 characters, grouped into 3 characters each, representing the permissions of the three groups of users for the file or directory. Permission characters use a dash to represent no permission, r for read-only, w for write, and x for executable.
Common parameters: -c report processing information when changes occur -R process the specified directory and all files in its subdirectories
Permission ranges:
u : the current user of the directory or file
g : the current group of the directory or file
o : users or groups other than the current user or group of the directory or file
a : all users and groups permission codes: r : read permission, represented by the number 4 w : write permission, represented by the number 2 x : execute permission, represented by the number 1 – : delete permission, represented by the number 0
s : special permission
Examples:
(1) Add executable permission for all users to the file t.log: chmod a+x t.log
(2) Revoke all original permissions, then grant read permission to the owner: chmod u=r t.log -c
(3) Assign read, write, and execute permissions (7) to the owner of file, assign read and execute permissions (5) to the group of file, and assign execute permission (1) to other users: chmod 751 t.log -c (or: 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
14、tar command
is used to compress and decompress files. tar itself does not have compression capabilities, only packaging capabilities. Compression and decompression are completed by calling other functions.
Understand the two concepts: packaging and compression. Packaging refers to turning a large number of files or directories into a single file; compression refers to reducing a large file into a smaller file using some compression algorithm.
Common parameters:
-c create a new compressed file -f specify the compressed file -r add files to an already compressed file -u add modified and existing files to 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 -v display the operation process related to gzip and bzip2 compression
Examples: Compress: gzip fileName .tar.gz and .tgz Decompress: gunzip filename.gz or gzip -d filename.gz Corresponding: tar zcvf filename.tar.gz tar zxvf filename.tar.gz bz2
Examples: Compress: bzip2 -z filename .tar.bz2 Decompress: bunzip filename.bz2 or bzip -d filename.bz2 Corresponding: tar jcvf filename.tar.gz Decompress: tar jxvf filename.tar.bz2
Examples:
(1) Package all files into a tar package: tar -cvf log.tar 1.log,2.log or tar -cvf log.*
(2) Package 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 just packaged file (must 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
15、ln command is used to create a synchronized link for a file at another location. When needed in different directories, there is no need to create the same file for each directory. The link created by ln reduces disk usage.
Link types: soft link and hard link Soft link:
1. Soft links exist in the form of paths. Similar to shortcuts in the Windows operating system.
2. Soft links can cross file systems, while hard links cannot.
3. Soft links can link to a non-existent file name.
4. Soft links can link to directories.
Hard link:
1. Hard links exist in the form of file copies. But do not occupy actual space.
2. Hard links are not allowed to create links to directories.
3. Hard links can only be created within the same file system.
Note:
First: The ln command maintains the synchronization of each linked file, meaning that no matter which one you modify, the other files will change accordingly;
Second: The links created by ln are divided into soft links and hard links. A soft link is created using ln -s source_file target_file, which will generate a mirror of the file at the selected location without occupying disk space. A hard link is created using ln source_file target_file, without the -s parameter, which will generate a file of the same size as the source file at the selected location. Whether soft link or hard link, 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 last destination is an existing directory, all previously specified files or directories will be copied to that 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 occur.
Common parameters:
-b delete and overwrite previously established links
-s soft link (symbolic link)
-v display detailed processing process
Examples:
(1) Create a soft 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 soft link for a directory: ln -sv /opt/soft/test/test3 /opt/soft/test/test5
16、date command
displays or sets the system’s date and time
Command parameters:
-d<string> displays the date and time specified by the string. The string must be enclosed in double quotes.
-s<string> sets the date and time according to the string. The string must be enclosed in double quotes.
-u displays GMT.
%H hour (00-23)
%I hour (00-12)
%M minute (00-59)
%s total seconds. The starting time is 1970-01-01 00:00:00 UTC.
%S seconds ( in local customary format))
%a abbreviation of the day of the week.
%A full name of the day of the week.
%d date ( represented as 01-31).
%D date ( including year, month, and day))
%m month ( represented as 01-12).
%y year ( represented as 00-99).
%Y year ( represented as a four-digit number))
Examples:
(1) Display the date of the next day: date +%Y%m%d –date=”+1 day” // Display the date of the next day
(2) Use the -d parameter: date -d “nov 22” This year’s 11 month 22 is Wednesday date -d ‘2 weeks’ 2 weeks later’s date: 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 month))
17、grep command is a powerful text search command, grep (Global Regular Expression Print) global regular expression search
The way grep works is that it searches for string patterns in one or more files. If the pattern includes spaces, it must be quoted, and all strings after the pattern 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 display n lines after the matching character
-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 pattern
-i ignore case
-l only list the names of files that contain the specified pattern
-f read keywords from a file
-n display the line numbers of matching content in the file
-R recursively search folders
grep’s regular expression:
^ # anchors the start of the line, e.g., ‘ ^grep’ matches all lines starting with grep.
$ # anchors the end of the line, e.g., ‘grep$’ matches all lines ending with grep.
. # matches a single non-newline character, e.g., ‘gr.p’ matches gr followed by any character, then p.
* # matches zero or more preceding characters, e.g., ‘*grep’ matches all lines with one or more spaces followed by grep.
.* # together represents any character.
[] # matches a character within a specified range, e.g., ‘[Gg]rep’ matches Grep and grep.
[^] # matches a character not in the specified range, e.g., ‘[^A-FH-Z]rep’ matches a letter not starting with A-R and T-Z followed by rep.
\(..\) # marks matching characters, e.g., ‘\(love\)’, love is marked as 1.
\< # anchors the start of a word, e.g., ‘\<grep’ matches lines containing words starting with grep.
\> # anchors the end of a word, e.g., ‘grep\>’ matches lines containing words ending with grep.
x\{m\} # repeats character x, m times, e.g., ‘0\{5\}’ matches lines containing 5 o’s.
x\{m,\} # repeats character x, at least m times, e.g., ‘o\{5,\}’ matches lines with at least 5 o’s.
x\{m,n\} # repeats character x, at least m times, but no more than n times, e.g., ‘o\{5,10\}’ matches lines with 5 to 10 o’s.
\w # matches word and digit characters, i.e., [A-Za-z0-9], e.g., ‘G\w*p’ matches a G followed by zero or more word or digit characters, then p.
\W #\w negation form, matches one or more non-word characters, such as punctuation.
\b # word boundary, e.g., ‘\bgrep\b’ matches only 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 only list files: grep -lR ‘^grep’ /tmp
(5) Find lines that do not start with x: grep ‘^[^x]’ test.txt
(6) Display lines containing ed or at: grep -E ‘ed|at’ test.txt
18、ps command ps (process status) is used to view the current running process status at once. If you need dynamic continuous results, use top to view processes in Linux.
There are 5 states for processes:
1. Running ( currently running or waiting in the run queue)
2. Interrupted ( sleeping, blocked, waiting for a condition to form or to receive a signal)
3. Uninterruptible ( received a signal that does not wake it and cannot run, the process must wait until an interrupt occurs)
4. Zombie ( the process has terminated, but the process descriptor exists until the parent process calls the wait4() system call to release it)
5. Stopped ( the process stops running after receiving SIGSTOP, SIGSTP, SIGTIN, SIGTOU signals)
The ps tool identifies 5 types of process status codes:
D Uninterruptible sleep (usually IO)
R Running runnable (on run queue)
S Interrupted sleeping
T Stopped 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 processes running in the current terminal -aux display all processes including other users’ processes
Examples: (1) Display all current processes, environment variables, and process relationships: ps -ef
(2) Display all current processes: ps -A
(3) Use with grep to find a specific process: ps -aux | grep apache
(4) Find the PID numbers related to the two services cron and syslog: ps aux | grep ‘(cron|syslog)’
19、top command displays relevant information about currently executing processes in the system, including process ID, memory usage, CPU usage, etc.
Common parameters:
-c display the complete process command -s secret mode -p < process number > specify the process to display -n < number of times > loop display times
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 zombieCpu(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 buffersSwap: 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 statistics of the current system situation.
The first line, task queue information, is the same as the 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 (during which the system has not restarted!) 2 users — currently, there are 2 users logged into the system load average: 1.15, 1.42, 1.44 — the three numbers after load average represent the load situation for 1 minute, 5 minutes, and 15 minutes. The load average data is calculated based on the number of active processes checked every 5 seconds. If this number divided by the number of logical CPUs results in a value greater than 5, it indicates that the system is overloaded. The second line, Tasks — tasks (processes), specific information description is as follows:
The system currently has a total of 206 processes, of which 1 is running, 205 are sleeping, 0 are in stopped state, and 0 are in zombie state.
The third line, CPU status information, specific attributes description is as follows: 5.9%us — percentage of CPU occupied by user space. 3.4%sy — percentage of CPU occupied by kernel space. 0.0%ni — percentage of CPU occupied by processes that have changed priority. 90.4%id — percentage of idle CPU. 0.0%wa — percentage of CPU waiting for IO. 0.0%hi — percentage of CPU occupied by hardware interrupts (Hardware IRQ). 0.2%si — percentage of CPU occupied by software interrupts (Software Interrupts).
Note: The CPU usage ratio here is different from the concept in Windows, and it is necessary to understand the relevant knowledge of user space and kernel space in the Linux system! The fourth line, memory status, specific information is as follows: 32949016k total — total physical memory (32GB) 14411180k used — total memory in use (14GB) 18537836k free — total free memory (18GB) 169884k buffers — amount of cached memory (169M)
The fifth line, swap partition information, specific information description is as follows: 32764556k total — total swap area (32GB) 0k used — total swap area in use (0K) 32764556k free — total free swap area (32GB) 3612636k cached — total buffered swap area (3.6GB)
The sixth line, empty line.
The seventh line and below: status monitoring of each process (task), item column information description is as follows: PID — process id USER — process owner PR — process priority NI — nice value. Negative values indicate high priority, positive values indicate low priority VIRT — total amount of virtual memory used by the process, in kb. VIRT=SWAP+RES RES — size of physical memory used by the process that has not been swapped out, in kb. RES=CODE+DATA SHR — size of shared memory, in kb. S — process status. D=uninterruptible sleep state R=running S=sleeping T=traced/stopped Z=zombie process %CPU — percentage of CPU time occupied since the last update %MEM — percentage of physical memory used by the process TIME+ — total CPU time used by the process, in units of 1/100 seconds COMMAND — process name (command name/command line)
top interactive commands
h display help information for top interactive commands
c switch to display command name and full command line
m sort by memory usage
P sort by CPU usage percentage
T sort by time/total time
W write current settings to ~/.toprc file
o or O change the order of displayed items
20、kill command
sends a specified signal to the corresponding process. If no type is specified, it will send SIGTERM (15) to terminate the specified process. If the program cannot be terminated, you can use the “-KILL” parameter, which sends the signal SIGKILL(9) , which will forcibly terminate the process. You can use the ps command or the jobs command to view the process number. The root user will affect the processes of users, while non-root users can only affect their own processes.
Common parameters:
-l signal, if you do not add the signal number parameter, using the “-l” parameter will list all signal names -a when processing the current process, do not limit the correspondence between command names and process numbers -p specify that the kill command only prints the process number of the relevant process without sending any signal -s specify the signal to send -u specify the user
Examples:
(1) First use ps to find the process pro1, then kill it: kill -9 $(ps -ef | grep pro1)