Bash shell Command (2), bashshell command

Source: Internet
Author: User
Tags character classes linux shell commands

Bash shell Command (2), bashshell command

In the previous article 《Bash shell Command (1)This section describes several simple linux shell commands.

Address:Http://, Reprinted, please specify the source address.

Monitoring procedure

1. Probe the process

To monitor processes, you need to use the ps command to output a lot of information about all programs running on the system.

By default, the pa command does not provide so much information.

The most common ps command is used to monitor the working conditions of background processes, because background processes do not have standard input/output settings such as the screen keyboard.
If you need to detect the situation, you can use the ps command.
The syntax of this command is as follows:
Ps [Option]
-E: displays all processes and environment variables.
-F full format
-H: No title is displayed.
-L long format
-W width output
A: displays all processes on the terminal, including those of other users.
R only displays Running Processes
X displays the processes without control terminals.

2. Real-time Monitoring Process

The ps command can only display information at a specific time point. If you want to observe the trend of processes frequently switching out of memory, the ps command is not convenient, and the top command is suitable


The first five lines are the overall statistical information area of the current system. Next we will look at the specific meaning of each line of information.

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

06:32:21-current system time

Up-the system has been running for 11 hours and 09 minutes

2 users-there are currently two users logging on to the system

Load average: 0.14, 0.09, 0.06-load average, the three numbers after which are 1 minute, 5 minutes, and 15 minutes respectively.

The load average data checks the number of active processes every five seconds and then calculates the value based on a specific algorithm. If this number is divided by the number of logical CPUs, the system is overloaded when the result is higher than 5.

Line 2: Tasks-task (process). The details are described as follows:

The system now has a total of 304 processes, of which one is running, 303 are sleep, 0 are stoped, and 0 are zombie.

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

1.0us-Percentage of CPU used by user space.

1.0sy-Percentage of CPU used by kernel space.

0.0ni-Percentage of CPU used by processes with changed priorities

98.0id-Percentage of idle CPU

0.0wa-Percentage of CPU occupied by I/O wait

0.0hi-Percentage of CPU used by Hardware IRQ

0.0si-Percentage of CPU used by Software Interrupts

Note: here, the CPU usage rate is different from that of windows. You need to understand the knowledge of linux user space and kernel space!

The fourth line shows the memory status. The details are as follows:

1010448 k total-total physical memory

911632 k used-total memory in use

98816 k free-total idle memory

51368 k buffers-cache memory size

The fifth line, swap partition information, the specific information is described as follows:

1046524 k total-total number of swap Areas

7816 k used-Total number of swap zones used

1038708 k free-Total number of idle swap Areas

318336 k cached-Total number of buffer swap zones


In Row 4, the total memory used (used) refers to the number of memories currently controlled by the system kernel. The total idle memory (free) is the amount of memory that the kernel has not yet incorporated into its control scope. The memory included in the kernel management is not always in use, but also the memory that can be reused in the past, the kernel does not return the reusable memory to free. Therefore, free memory will become fewer and fewer on linux, but you don't have to worry about it.

If you calculate the number of available memory out of habit, there is an approximate formula: free in the fourth row + buffers in the fourth row + cached in the fifth row, calculate the available memory of the server according to this formula.

For memory monitoring, we need to monitor the used of the fifth-line swap partition in top. If this value is constantly changing, it means that the kernel is constantly exchanging data between memory and swap, this is the real insufficient memory.

The sixth line is empty.

Row 7: monitors the status of each process (task). The project column information is described as follows:

PID-process id

USER-process owner

PR-process priority

NI-nice value. A negative value indicates a high priority, and a positive value indicates a low priority.

VIRT-Total virtual memory used by the process, in kb. VIRT = SWAP + RES

RES-physical memory used by the process, not swapped out, in kb. RES = CODE + DATA

SHR-shared memory size, in kb

S-Process status. D = non-disruptive sleep state R = running S = sleep T = tracking/stopping Z = botnets

% 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 the unit of 1/100 seconds

COMMAND-process name (COMMAND name/COMMAND line)

Top common parameters are as follows:

-Batch B Processing

-C: display the complete governance command

-I ignore the failure process

-S security mode

-S cumulative Mode

-I <time> set the interval

-U <User Name> specifies the user name

-P <process number> specifies the process

-N <times> Number of cycles displayed

3. Process Termination

In linux, processes communicate through signals. The signal of a process is to reserve a message, and the process can recognize it and respond to it.

The linux Process signal is as follows:

On linux, there are two commands that can send process signals to running processes: kill and killall.

Kill command

The kill command in Linux is used to terminate the running of a specified process. It is a common command for process management in Linux. Generally, you can use Ctrl + C to terminate a foreground process. However, for a background process, you must use the kill command to terminate it, we need to first use ps/pidof/pstree/top and other tools to obtain the process PID, and then use the kill command to kill the process. The kill command ends a process by sending a specified signal to the process. By default, the TERM signal numbered 15 is used. The TERM signal terminates all processes that cannot capture the signal. For processes that can capture this signal, use the kill signal numbered 9 to forcibly "kill" the process.

1. Command Format:

Kill [parameter] [process number]

2. command functions:

Sends the specified signal to the corresponding process. If no model is specified, SIGTERM (15) is sent to terminate the specified process. If the program cannot be terminated and the "-KILL" parameter is available and the signal sent is SIGKILL (9), the process is forcibly terminated. You can run the ps command or the jobs command to view the process number. Root users will affect user processes. Non-root users can only affect their processes.

3. command parameters:

-L signal. If no signal serial number parameter is added, the "-l" parameter is used to list all signal names.

-When processing the current process, a does not limit the correspondence between command names and process numbers.

-P: Specify the kill command to print only the process number of the relevant process without sending any signal.

-S indicates the sending signal

-U indicates the user


1. The kill command can contain the signal number option or not. If there is no signal number, the kill command will send a termination signal (15), which can be captured by the process so that the process can clear and release resources before exiting. You can also use kill to send specific signals to the process. For example:

Kill-2 123

The result is equivalent to pressing Ctrl + C when running a process with a PID of 123 on the front end. However, common users can only use the kill command without the signal parameter or use a maximum of-9 signals.

2. kill can contain a process ID as a parameter. When sending signals to these processes with kill, they must be the masters of these processes. An error message is returned when you try to undo a process without permission or undo a non-existent process.

3. You can send signals to or terminate multiple processes.

4. After kill successfully sends a signal, the shell will display the process termination information on the screen. Sometimes this information is not immediately displayed. It is only displayed when the shell command prompt appears again by pressing Enter.

5. It should be noted that the process is forcibly terminated by a signal, which often brings some side effects, such as data loss or the terminal cannot be restored to normal. When sending a signal, you must be careful. Only when you have to do so can you use the kill signal (9), because the process cannot capture it first. To cancel all background jobs, enter kill 0. Some commands run in the background will start multiple processes, and it is very troublesome to trace and find the PID of all processes to be killed. Kill 0 is an effective method to terminate all processes started by the current shell.

The kill command sends a signal to the process through the PID (process number). By default, the kill command sends a TERM signal to all the PID listed in the command line. Unfortunately, you can only use the PID of the process instead of the command name, so the kill command is sometimes not useful.

To send a process signal, you must be the owner of the process or log on as the root user.

The killall command is very powerful. It supports killing a process by the process name rather than the process number. The killall command also supports wildcards, which are useful when the system becomes slow due to excessive load.

Disk Space Detection

1. Mount storage media

In Linux, all disks are mounted to a virtual directory. before using the new storage media, you need to put it under the virtual directory.

Most Linux distributions can automatically mount the specified removable storage media.

(1) mount command

By default, the mount command will output the list of devices mounted on the current system:

Format: mount [-parameter] [device name] [mount point]
Common parameters include:

Umount command
When a Removable device is removed from a Linux system, it cannot be directly removed from the system. Instead, you should uninstall the device first. The command for detaching the device is called umount.

The umount command format is very simple:

Umount [directory | device]

The umount command allows you to specify the device to be detached through a device file or a mount point. If any program is using a file on the device, the system will not allow you to uninstall it.

(2) Use the df command

Command Format:

Df [Option] [file]

Required parameters:

-A list of all file systems

-H: Easy reading mode display

-H is equal to "-h", but the formula is 1 K = 1000, instead of 1 K = 1024.

-I: displays inode information.

The-k block is 1024 bytes.

-L only displays the local file system

-The m block is 1048576 bytes.

-- No-sync ignore the sync command

-P output format is POSIX

-- Sync: run the sync command before obtaining disk information.

-T file system type


Select parameters:

-- Block-size = <block size> specifies the block size.

-T <file system type> only displays the disk information of the selected File System

-X <file system type> does not display the disk information of the selected File System

-- Help: displays help information.

-- Version: displays version information.

The df command is used to easily view the usage of all mounted disks:


Column 1: Device File Location

Column 2: How many 1024-byte blocks can be accommodated

Column 3: How many blocks of 1024 bytes are used

Column 4: How many blocks of 1024 bytes are available?

Column 5: Percentage of used space

Column 6: mount point on which the device is mounted

(3) Use the du command

1. Command Format:

Du [Option] [file]

2. command functions:

Displays the disk space used by each file and directory.

3. command parameters:

-A or-all indicates the size of individual files in the directory.

-B or-bytes: displays the size of directories or files in bytes.

-C or -- total not only displays the size of individual directories or files, but also the total number of all directories or files.

-K or -- kilobytes is output in KB (1024 bytes.

-M or -- megabytes is output in MB.

-S or -- summarize only displays the total, and only lists the last added total value.

-H or -- human-readable is in the unit of K, M, and G to improve information readability.

-X or -- one-file-xystem is based on the file system at the beginning of processing. If it encounters a different file system directory, it is skipped.

-L <symbolic link> or -- dereference <symbolic link> shows the source file size of the specified symbolic link in the option.

-S or -- separate-dirs displays the size of individual directories in hours without the size of their subdirectories.

-X <File> or -- exclude-from = <File> specifies the directory or file in <File>.

-- Exclude = <directory or File> skips the specified directory or file.

-D or -- dereference-args displays the source file size of the specified symbolic link.

-H or -- si is the same as-h, but K, M, and G are measured in 1000 units.

-L or -- count-links repeat the hardware link file.

Process data files

1. Sort data

By default, the sort command sorts data rows in text files according to the sorting rules of the default language you specified for this session. The sort command helps us sort data rows based on different data types, its syntax and common parameter formats:

  Sort [-bcfmnscn] [source file] [-o output file]
Note: sort can sort the content of text files by unit of action.

-B ignores the leading space characters in each line.
-C: Check whether the files are sorted in order.
-F indicates that uppercase and lowercase letters are ignored during sorting.
-M sorts the first three letters by the abbreviation of the month.
-N is sorted by the value size.
-O <output file> stores the sorted results to the specified file.
-R is sorted in reverse order.
-T <delimiter> specifies the column delimiter used for sorting.
-K: select the range in which the data is sorted.

2. search data

In Linux, The grep command is a powerful text search tool that uses regular expressions to search for text and print Matching lines. Grep stands for Global Regular Expression Print, which indicates the Global Regular Expression version. Its permission is granted to all users.

Grep works like this. it searches for string templates in one or more files. If the template contains spaces, it must be referenced. All strings after the template are treated as file names. The search result is sent to the standard output without affecting the content of the original file.

Grep can be used in shell scripts because grep returns a status value to indicate the search status. If the template search is successful, 0 is returned. If the search is unsuccessful, 1 is returned, if the searched file does not exist, 2 is returned. We can use these return values to automate text processing.

1. Command Format:

Grep [option] pattern file

2. command functions:

Specific Characters Used for filtering/searching. Regular Expressions can be used in combination with multiple commands.

3. command parameters:

-A -- text # Do not ignore binary data.

-A <display number of rows> -- after-context = <display number of rows> # In addition to displaying the column that conforms to the template style, the content after the row is displayed.

-B -- byte-offset # indicates the number of the first character of the line before the line that conforms to the style is displayed.

-B <display number of rows> -- before-context = <display number of rows> # In addition to the line that conforms to the style, and the content before the line is displayed.

-C -- count # calculate the number of columns that match the style.

-C <display number of rows> -- context = <display number of rows> or-<display number of rows> # In addition to the line that conforms to the style, and the content before and after the line is displayed.

-D <action> -- directories = <action> # this parameter is required when you specify a directory rather than a file to be searched. Otherwise, the grep command returns information and stops the action.

-E <template style> -- regexp = <template style> # specify a string as the style for searching the file content.

-E -- extended-regexp # Use the style as an extended normal notation.

-F <rule file> -- file = <rule file> # specifies the rule file, which contains one or more rule styles, so that grep can find the file content that meets the rule conditions, the format is one rule style per line.

-F -- fixed-regexp # lists the styles as fixed strings.

-G -- basic-regexp # use styles as normal notation.

-H -- no-filename # The name of the file to which the row conforms to the style is not displayed.

-H -- with-filename # indicates the name of the file to which the row belongs before the row that conforms to the style is displayed.

-I -- ignore-case # ignore case sensitivity differences.

-L -- file-with-matches # lists the names of objects whose contents match the specified style.

-L -- files-without-match # lists the names of files whose contents do not conform to the specified style.

-N -- line-number # indicates the number of columns of the row before the row that conforms to the style is displayed.

-Q -- quiet or -- silent # No information is displayed.

-R -- recursive # the effect of this parameter is the same as that of the specified "-d recurse" parameter.

-S -- no-messages # the error message is not displayed.

-V -- revert-match # displays all rows that do not contain matched text.

-V -- version # displays the version information.

-W -- word-regexp # Only columns with full-text matching are displayed.

-X -- line-regexp # Only displays columns that match the full column.

-Y # the effect of this parameter is the same as that of the specified "-I" parameter.

4. Rule expression:

Grep rule expression:

^ # Start of the anchor row: '^ grep' matches all rows starting with grep.

$ # End of the anchor row, for example, 'grep $ 'matches all rows ending with grep.

. # Match a non-linefeed character, for example, 'gr. P' matches gr followed by any character, followed by p.

* # Match zero or multiple previous characters, for example, '* grep' matches all rows followed by one or more spaces.

. * # Represents any character together.

[] # Match a character in a specified range, for example, '[Gg] rep' matches Grep and grep.

[^] # Match a character that is not within the specified range, for example, '[^ A-FH-Z] rep' match a line that does not start with a letter that does not contain the A-R and T-Z, followed by rep.

\ (.. \) # MARK matching characters, such as '\ (love \)', and love is marked as 1.

\ <# Specifies the start of a word, for example, '\ <grep' matches a row that contains a word starting with grep.

\># Specify the end of a word, such as 'grep \>.

X \ {m \} # repeated characters x, m times, for example, '0 \ {5 \} 'match rows containing 5 o.

X \ {m, \} # repeated characters x, at least m times, such as: 'O \ {5, \} 'matching rows with at least 5 o.

X \ {m, n \} # repeated character x, at least m times, no more than n times, for example, 'O \ {5, 10 \} 'matches rows of 5-10 o.

\ W # match text and numeric characters, that is, [A-Za-z0-9], such as: 'G \ w * P' match with G followed by zero or more characters or numbers, then p.

The inverse form of \ W # \ w. It matches one or more non-word characters, such as periods and periods.

\ B # The word lock. For example, '\ bgrep \ B' matches only grep.

POSIX characters:

To ensure one character encoding in different countries, POSIX (The Portable Operating System Interface) adds special character classes, such as [: alnum:] is another way of writing [A-Za-z0-9. Put them in the [] sign to become A regular expression, such as [A-Za-z0-9] or [[: alnum:]. In linux, grep supports POSIX character classes except fgrep.

[: Alnum:] # numbers and characters

[: Alpha:] # text characters

[: Digit:] # numeric characters

[: Graph:] # non-empty characters (non-space, control characters)

[: Lower:] # lowercase characters

[: Cntrl:] # control characters

[: Print:] # non-empty characters (including spaces)

[: Punct:] # punctuation marks

[: Space:] # All blank characters (new lines, spaces, and tabs)

[: Upper:] # uppercase characters

[: Xdigit:] # hexadecimal number (0-9, a-f, A-F)

Compressed Data

Linux File compression tool (compress is rarely seen in Linux ):

1. bzip2 Tool

It is particularly popular in the field of compressing large binary files. The bzip2 package has the following tools:

Bzip2: Used to compress files

Bzcat: used to display the content of compressed text files

Bunzip2: Used to decompress the. bz2 File

Bzip2recover: Used to restore damaged compressed files

2. gzip Tool

The most popular File compression tool in linux. This package contains the following tools:

Gzip: Used to compress files

Gzcat: used to view the content of compressed text files

Gunzip: used to extract files

3. zip Tool

There are five linux zip packages:

Zip: Create a compressed file that contains the specified file and directory.

Zipcloak: creates an encrypted compressed file that contains the specified file and directory.

Zipnote: extract comments from the zip file

Zipsplit: splits an existing zip file into multiple smaller, fixed-size files.

Unzip: Extract files and directories from compressed zip files

You can use the following command to view all the parameters of the zip command:

$ Zip

Archive data

The most widely used archive tool on Unix and Linux is the tar command.

The tar command can create files for linux Files And Directories. Using tar, you can create a file (backup file) for a specific file, change the file in the file, or add a new file to the file. Tar was originally used to create files on tape. Now, you can create files on any device. Using the tar command, you can package a large number of files and directories into one file, which is very useful for backing up files or combining several files into one file for network transmission.

First, we need to clarify two concepts: Packaging and compression. Packaging refers to converting a large number of files or directories into a total file. Compression refers to converting a large file into a small file through some compression algorithms.

Why do we need to differentiate these two concepts? This is because many Linux compression programs can only compress one file. In this way, when you want to compress a large number of files, you must first compress these files into a package (tar command ), then use the compression program to compress (gzip bzip2 command ).

At the end of lifecycle. After the tar package is generated, other programs can be used for compression.

1. Command Format:

Tar [required parameters] [select parameters] [files]

2. command functions:

Used to compress and decompress files. Tar itself does not have the compression function. It is implemented by calling the compression function.

3. command parameters:

Necessary parameters are as follows:

-A adds A compressed file to an existing compressed file.

-B. Set the block size.

-C create a new compressed file

-D record file difference

-R: add files to compressed files.

-U added and changed existing files to existing compressed files.

-X Extract files from compressed files

-T display the compressed file content

-Z supports gzip file Extraction

-J supports bzip2 File Extraction

-Z supports compress file Extraction

-V shows the operation process

-L file system boundary settings

-K keep the original file not to overwrite

-M: The reserved file is not overwritten.

-W confirm the correctness of the compressed file


The optional parameters are as follows:

-B: set the number of blocks.

-C switch to the specified directory

-F: Specify the compressed file

-- Help: displays help information.

-- Version: displays version information.


Bash shell Command

At ---- schedule, check, and delete jobs in the queue
Cat ---- connect the file and print it to the standard output
Cd ---- Change directory to be able to process absolute and relative paths
Chmod ---- change the file protection permission
Chown-change the owner and group of Files
Clear ---- clear the screen (like cls in DOS)
Cp ---- copy an object
Crontab-operate the daemon and execution schedule of each user
Date ---- print or set the system date and time
Dd ---- copy an object (and convert it at the same time)
Df ---- report the remaining disk space
Du ---- report disk space usage
File ---- test file and directory types
Find ---- search for files in a directory
Grep ---- search for matched rows in the file and Output
Gzip-compress or expand a file
Head ---- display the first few lines of the file
History ---- display historical Command records
Kill ---- abort a process
Last ---- shows how many users or terminals have logged on to the machine
Less ---- you want to use the more command to display files by PAGE
Ln ---- establish a connection Between Files
Ls ---- list files in the current directory
Man ---- display online manuals with certain formats
More ---- the command can read the text page by page
Mount ---- install a File System
Mv ---- rename the file
Passwd ---- set the User Password
Ps ---- command to list Running Processes
Reboot ---- restart the system
Rm ---- command used to delete files
Su ---- create and edit Unix archive files
Tar ---- create and edit Unix archive files
Touch ---- change the time parameter of the file
Wc ---- count the number of bytes, number of words, and number of rows in a file
Who ---- view other login users
Which ---- which -- display the full path of the command
Ping ---- command-determine whether the machine on the network can reach or reach the speed
Output redirection
Understanding processes


In Linux, there are two operation interfaces: X Window mode (KDE by default) and Console mode (Console ). The two interfaces are similar to Windows and DOS.

If you want to change to Console mode in X Window mode, you only need to press Alt + F1 (or F2... F6) key. A new waiting window will appear on the screen. You can log on to the system again in Console mode. If you want to return to X Window mode in Console mode, press Ctrl + Alt + F7 at the same time.

If the X Window mode is not enabled and you want to start the X Window mode from the console mode, enter startx (or kdm) in the Console mode to start the X Window.

In the above two chapters, we have introduced the operation of the X Window (KDE by default). In this chapter and the next chapter, we will mainly discuss the operations in the Console mode, the corresponding KDE operation will also be inserted between them.

6.1 start and close the system
Start the system
If you have installed LILO during the installation process, you can start the system. When LILO is started, the screen displays:


Click the Tab key to display all operating systems that can be started. Enter the name of the displayed operating system to start the corresponding operating system. Type Linux to start BluePoint Linux & 127. If you press the Enter key directly or wait for 5 seconds, you can also start the BluePoint Linux & 127; operating system.

Another way to start linux is to run the command in DOS/WINDOWS... the remaining full text>

In bash shell, if [-f $2] and echo-e are

If [-f $2]
If followed by a test Statement, which is equivalent to the test command in [].-f $2 generally means to check whether the second location parameter exists.

Echo-e is usually followed by parameters,
-E if the parameter contains the following characters, it will be specially processed and will not be treated as a general
Text output:
\ A sends an alert;
\ B Delete the previous character;
\ C does not end with a line break;
\ F line feed, but the cursor remains at the original position;
\ N wrap and move the cursor to the beginning of the line;
\ R move the cursor to the beginning of the line without line breaks;
\ T Insert tab;
\ V is the same as \ f;
\ Insert \ characters;
\ Nnn inserts the ASCII characters represented by nnn (octal;
Echo Syntax: echo [-ne] [String] or echo [-- help] [-- version]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.