This is the shell command and command execution, the article commands here to download Command command execution, the previous one is the shell variables, condition judgments, control structures and functions, the previous section on what is Shell, pipeline and redirection, as the programming language of the shell.
The 2.6.5 command can execute two types of commands within a shell script. A class is a "normal" command that can be executed at the command prompt, as well as an external command, a "built-in" command, and an internal command. Built-in commands are implemented inside the shell, and they cannot be called as external programs. Most internal commands then also provide a version of the program that runs independently, which is part of the POSIX specification.
The 1.break command jumps out of the for,while or until loop before the control condition is met. By default, break jumps only one layer of loop.
2.: Command colon: command is an empty command, which is occasionally used to simplify conditional logic, equivalent to an alias of true. Because it is a built-in command, it runs faster than true, but its output is less readable. For example, you can use while: to implement an infinite loop instead of the more common while true.
3.continue Command This command causes the for, while, or until loop to skip to the next loop to continue execution, and the loop variable takes the next value in the Loop list.
4: Command Point
. Commands for executing commands in the current shell:
.. /shell_script
Typically, when a script executes an external command or script, it creates a new environment (a child shell), which is executed in the new environment, which is discarded after the command is executed, leaving the exit code back to the parent shell. But the external source command and the Point command (which are synonyms) use the same shell that called the script when you execute the command listed in the script.
Because the shell script is executed in a newly created environment by default, any modifications made by the script to environment variables are lost. The point command allows the execution of the scripting program to change the current environment. This command is often useful when you want to use a script as a "wrapper" to set up an environment for some of the other commands that are executed later.
In a shell script, the point command is somewhat similar to the # include directive in C or C + +, which executes a command in the current context and can be used to combine variables and function definitions into a script.
5.echo command Although X/open recommends using the printf command in the shell now, it is often used to output a string with a newline character at the end with the echo command.
A common question is how to
Remove line break, Linux is commonly used in the following ways:
echo-n "string to Output"
6.eval command
eval command allows evaluation of parameters, which is a shell's built-in command, usually not in the form of a separate command.
foo=10
X=foo
Y= ' $ ' $x
Echo $y
foo=10
X=foo
Eval y= ' $ ' $x
Echo $y
The previous result output is $foo, and the last result is output 10.
The eval command is a bit like an extra $, it gives the value of a variable value。
A bit like a pointer? $ similar to *, take out the content that the address points to.
The 7.exec command EXEC command is used in two different ways, and its typical use is to replace the current shell with a different program. For example:
EXEC Wall "Thanks for all the fish"
This command in the script replaces the current shell with the wall command, and the code behind the EXEC command in the script is not executed because the shell that executes the script no longer exists.
The 8.exit n command exit command causes the script to end running with exit code N. If you use this command in any of the interactive Shell's command prompt, it will cause the system to exit. If a script program is allowed to exit without specifying an exit state, the state of the last executed command in the script is used as the return value. It is always a good practice to provide an exit code in a scripting program.
In shell script programming, exit code 0 indicates success.
Here is a simple example, if a file named. Profile exists in the current directory, it returns 0 for success, and 1 for failure:
#!/bin/sh
If [-F *.profile]
Then
Exit 0
Fi
Exit 1
If you are pursuing a more concise version:
[-F *.profile] && Exit 0 | | Exit 1
9.export command
Export command Exports the variable that is its parameter to the child shelland make it valid in the child shell. In
defaultCase, in a
The variables created in the shell are not available in the lower shell of the shell callOf The export command creates its own parameters as an environment variable, which can be seen by other scripts and programs called by the current program. From a more technical point of view,
The exported variable forms the environment variable of any child process derived from the shell.
Once a variable is exported by the shell, it can be used by any script invoked by the shell, or by any shell that is subsequently invoked in turn.
The 10.expr Command expr command evaluates its arguments as an expression. The most common use of this is to perform simple mathematical operations:
x= ' expr $x + 1 ' (Note that this command does not seem to have the corresponding result, use $ () to achieve the purpose, and later found that the anti-quote is the key above the tab, not the single quotation marks)
The anti-quote ' character causes X to be evaluated as the command expr $x + 1 execution result. You can also use the syntax $ () to replace the anti-quote "', as follows:
x=$ (expr $x + 1)
Expression Evaluation Description
Expr1 | EXPR2 if expr1 nonzero, equals expr1, otherwise equals expr2
Expr1 & Expr2 As long as one expression is zero, it is equal to zero, otherwise equal to EXPR1
In newer scripts, the expr command is usually replaced with the
more efficient $ ((...)) Grammar。
11.printf command only the new version of the shell provides the printf command, and the X/open specification suggests that we should use it instead of the echo command to produce formatted output.
printf "%s\n" Hello
printf "%s%d\t%s" "Hi There" people
The purpose of the 12.return Command return command is to return the function. The return command has a numeric parameter, which is considered to be the return value of the function in the script that invokes the function. If no parameters are specified, the return command returns the exit code of the last command by default.
The role of the 13.set command set command is to set parameter variables for the shell. The output of many commands is a space-delimited value, which is useful if you need to use a field in the output result.
Suppose you want to use the name of the current month in a shell script. The system itself provides a date command whose output contains the name of the month as a string, but it needs to be separated from the rest of the region. The set command and the $ (...) can be Structure to execute the date command and return the desired result. The output of the date command takes a month string as its second argument:
#!/bin/sh
echo the date is $ (date)
Set $ (date)
echo the month is $
Exit 0
This program sets the output of the date command to the argument list, and then obtains the month through the positional parameter, $.
With this example, you can see how the date command extracts the positional parameters, and because the output of the date command is affected by the local language, you should use the date +%b command to extract the month name.
The execution of the shell can be controlled through the set command and its parameters, the most commonly used command format is Set-x, which allows a script to track the actual command it is currently executing.
The 14.shift command shift command shifts all parameter variables to the left one position, making the $1,$3 into a $ $, and so on. The original value of $ will be discarded, and the $ is unchanged. If a numeric argument is specified when the shift command is called, all parameters are shifted left for the specified number of times. $*,[email protected] and $ #等其他变量也将根据参数变量的安排而作相应的变动.
The 15.trap Command Trap command specifies the action to be taken after receiving a signal, and a common user of the trap command is to complete the cleanup work when the script is interrupted. Historically, the shell always used numbers to represent the signal, but the new script should use the name of the signal, which is defined in the header file signal.h, and the sig prefix needs to be omitted when using the signal name. You can enter the command trap-l at the command prompt to view the signal number and its associated name.
The trap command has two parameters, the first parameter is the action to be taken when the specified signal is received, and the second parameter is the name of the signal to be processed.
Trap command Signal
The script is usually interpreted from top to bottom, so you must specify the trap command before the part of the code that you want to protect.
Signals are those events that are sent asynchronously to a program, which, by default, usually terminates the operation of a program.
If you want to reset the way a signal is processed to its default value, you only need to set the command to-. If you want to ignore a signal, set the command to the empty string '. A trap command without parameters will list the current set of signals and the list of its actions.
Signal description
HUP (1) hangs, usually caused by terminal drop or user exit
INT (2) interrupt, usually caused by pressing CTRL + C key combination
Quit (3) exit, usually caused by pressing the ctrl+\ combination
ABRT (6) termination, usually caused by some serious execution error
ALRM (14) Alarm, typically used to process timeouts
Term (15), usually sent at system shutdown
The purpose of the 16.unset command unset command is to remove variables or functions from the environment, which cannot delete read-only variables defined by the shell itself (such as IFS)
17. Two other useful commands and regular expressions, although not part of the shell, are often used in shell programs. It also introduces regular expressions, a pattern-matching feature that appears in all Linux and associated programs.
Find Command
The Find command is used to search for files.
Find/-name Test-print
This command starts from the root directory and looks for a file with the file name test and outputs the full path to the file.
The execution of this command can then take a long time, and the hard drive of the Windows machine on the network will rotate at a high speed. This is because the Linux machine mounts a large chunk of the Windows machine's file system, and it looks as if the Windows file system is also being searched, even though we know that the files to look for should be on the Linux machine.
This is the time for the first option to work, and if you specify the-mount option, you can tell the find command not to search for additional file system directories that are mounted. This will make the search faster.
The full syntax format for the Find command is as follows:
find [path] [options] [tests] [actions]
Path section: You can use either an absolute path, such as/bin, or a relative path, such as. You can also specify multiple paths, such as find/var/home, if desired.
The Find command has a number of options available, such as:
Option meaning
-depth Search the contents of the directory before viewing the directory itself
-follow Follow Symbolic Links
-maxdepths n Max Search N-tier directory
-mount (or-xdev) does not search for directories in other file systems
Test meaning
-type C files are of type C, most commonly D (directories) and F (normal file)
operator meaning
! -not Test Inversion
-a-and Two tests must be true
-o-or Two tests have a must be true
Search for files that are later than file Test28 in the current directory:
$ find. -newer Test28-print
You can see that the results also contain the current directory, and if you want only normal files, add an additional test-type F
$ find.-newer test28-type f-print
You can combine conditional searches to find files that contain _ in the current directory or files that are later than test28
$ find. \ (-newer test28-o-name "*_*" \)-type F-print
Because parentheses have a special meaning for the shell, you must use backslashes to refer to parentheses.
grep Command
This name represents the generic regular expression parser (general Regular Expresssion Parser, abbreviated as GREP) and uses the grep command to search for strings in the file. A common use is to use grep as a command to pass to-exec when using the Find command.
The grep command uses an option, a pattern to match, and a file to search, and its syntax is as follows:
grep [options] pattern [files]
If no file name is provided, the grep command searches for standard input.
Option meaning
- C Output matches the number of rows instead of the output matching rows
-e Enable Extended expression
-H cancels the normal prefix for each output line, which is the file name that matches the query pattern
-I ignores case
-l lists only the file names that contain the matching rows, not the true matching rows
-V Reverse the matching pattern, that is, the search does not match the row but the matching row
For example:
$ grep in test1
Show rows in Test1 that contain in
$ grep-c in test1 test2 test3
Shows the number of rows in Test1,test2,test3 that contain in
$ grep-c-V in test1 test2
Displays the number of rows in the test1,test2 that do not contain in
Regular expressions
The most common special characters in a regular expression are as follows:
Character meaning
^ point to the beginning of a line
$ points to the end of a line
. Any single character
[] The square brackets contain a range of characters, any one of which can be matched, such as a~e, or
Precede the character range with ^ to indicate the use of the inverse character range.
Some useful special matching patterns can also be used in square brackets, as follows:
Match pattern meaning
[: Alnum:] Letters and numeric characters
[: Alpha:] Letter
[: ASCII:] ASCII characters
[: Blank:] Space or Tab
[: Cntrl:] ASCII control characters
[:d Igit:] Number
[: Graph:] Non-controlled, non-whitespace characters
[: Lower:] lowercase letters
[:p rint:] printable characters
[:p UNCT:] punctuation characters
[: Space:] white space characters
[: Upper:] Uppercase
[: xdigit:] hexadecimal digits
For example:
$ grep e$ test1
Find the line ending with E in test1
$ grep ^e test1 test2
Find lines that start with E in Test1,test2
$ grep a[[:blank:]] test1 test2
Displays the word ending in E in Test1,test2
$ grep th. [[: Space:]] test1 test2 test3
Displays the 3-letter word that begins with th in test1,test2,test3, with characters. To match an extra character
$ GREP-E [a-z]\{10\} test1 test2 test3
Finds all lowercase letters that display only 10 characters in a test1,test2,test3.
When you write a script for the execution of a 2.6.6 command, you need to
captures the execution result of a command, and use it in the Shell script program. That
executes a command and puts the output of the command into a variable。
All new scripting programs should
use $ (...) Form,
The result of $ (command) is the output of one of the commands。 Note that this is not the exit state of the command, but rather the output of its string form. For example:
echo the current directory is $PWD
echo the current users is $ (WHO)
If you want to put the result of a command into a variable, you can assign it the usual method, as follows:
Value=$ (WHO)
Echo $value
This ability to put command execution results into variables is very powerful, making it easy to use existing commands in a script and capture their output. If you need to convert the output of a command to a set of parameters on the standard output and use them as parameters for another program, the command Xargs can accomplish this task.
1. The description of the expr command before the arithmetic extension can handle some simple arithmetic commands, but the command executes quite slowly because it needs to invoke a new shell to process the expr command.
A better way to update is
use $ ((...)) Extended。 Enclose the expression that is ready to be evaluated in $ ((...)) Can perform simple arithmetic operations more efficiently. As shown below:
X=0
While ["$x"-ne 10]
Do
Echo $x
x=$ (($x + 1))
Done
Note that this is with x=$ (...). Command differs, two pairs of parentheses are used for arithmetic substitution, and the pair of parentheses we saw previously were used for command execution and fetch output.
??? The doubt is that X is treated as a string to judge the conditionAnd also get the same output ("$x"! = 10)
2. A simple parameter assignment and extension is described before the parameter extension, as follows:
Foo=fred
Echo $foo
??? Doubts about the assignment in the shell, a little bit of pointer-passing feeling, the Foo variable stores Fred's pointer, takes the address operator * Similar to $, gets the contents of the variable
If you want to write a script that handles Test1 and test2 two files, you might write:
For I in 1 2
Do
./testi
Done
In each cycle, the./testi not found is found.
The problem is that the./testi variable cannot be replaced, in order to protect the extension similar to the $i part of the variable name, you need to
Put i in curly braces, as shown below
. Test${i}
Thus, in each loop, the value of the variable i is replaced by $ (i), the correct file name is given, and the value of the parameter is substituted into a string.
Multiple parameter substitution methods can be used in the shell, which often provides an ingenious solution for multi-parameter processing problems.
parameter Extension Description
${param:-default} If Param is empty, set it to the value of default
#{#param} gives the length of the Param
${param%word} removes the smallest part that matches word from the tail of Param, and then returns the remainder
${param%%word} removes the longest part that matches word from the tail of Param, and then returns the remainder
${param#word} removes the smallest part that matches word from the head of Param, and then returns the remainder
${param# #word} Remove the longest part that matches word from the head of Param and return to the remainder
These substitutions are often useful when working with strings, especially the last 4 parameter expansion methods that partially delete a string, which is useful when working with filenames and paths.
--shell Programming for Linux Programming (chapter II)