Author: Thank you! Reading carefully gives you a day to learn about the Shell's basic grammar rules.
1. Create and run shell programs
What is a shell program? The shell program is a simple one that contains several lines
The file for the shell or Linux command.
Like programs that write high-level languages, writing a shell program requires a text editor. such as VI.
In the text editing environment, according to the shell syntax rules, enter some shell/linux command line, form a complete
The entire program file.
There are three ways to execute Shell program files
(1) #chmod +x file
(2) #sh file
(3) #. File
When writing the shell, the first line must indicate that the system needs the shell to interpret your shell program, such as: #!
/bin/bash,
#! /BIN/CSH,/BIN/TCSH, or #!? /bin/pdksh.
Variables in the 2.shell
(1) Common system variables
$ #: Number of Save program command-line arguments
$ ? : Save return code for previous command
$0: Save program Name
$ *: to ("$ $ ...") Saves all input command-line arguments in the form of
$ @: With ("$" "$" ...) Saves all input command-line arguments in the form of
(2) Defining variables
The shell language is a non-type interpreted language, and it is not necessary to declare variables in advance, as in C++/java language programming. Give
A variable assignment is actually defined as a variable.
In all of the shells supported by Linux, you can assign a value to a variable with an assignment symbol (=).
Such as:
Abc=9 (Bash/pdksh cannot leave spaces on both sides of the equals sign)
Set ABC = 9 (tcsh/csh)
Because the shell program's variables are untyped, the user can use the same variable to store characters and sometimes save
Put an integer.
Such as:
NAME=ABC (Bash/pdksh)
Set name = ABC (TCSH)
After assigning a variable, simply precede the variable with a $ reference.
Such as:
Echo $ABC
(3) Position variable
When you run a shell program that supports multiple command-line arguments, the values of these variables are stored separately in the position variable
The first parameter is stored in position variable 1, the second parameter is stored in position variable 2, and so on ..., shell
Keep these variables, and do not allow users to define them in a way that allows them to be defined. Same variables, reference them with the $ symbol.
How to use quotation marks in 3.shell
The shell uses quotation marks (single quotation marks/double quotes) and backslashes ("\") to mask some special characters to the shell interpreter
. The inverted quotation mark (") has a special meaning for the shell.
Such as:
Abc= "How is You" (Bash/pdksh)
Set abc = "How Is You" (TCSH)
This command line assigns a string of three words to the variable ABC as a whole.
Abc1= ' @LOGNAME, how is you! ' (Bash/pdksh)
Set abc1= ' $LOGNAME, how is you! ' (TCSH)
Abc2= "$LOGNAME, How is you!" (Bash/pdksh)
Set abc2= "$LOGNAME, How is you!" (TCSH)
The logname variable is a shell variable that holds the current user name, assuming that his current value is: Wang. Execute two Lives
After the order, the content of ABC1 is logname, how is you!. And ABC2 's content is, Wang, how is you!.
Like single quotes, backslashes can also block all special characters. But he can only block one character at a time.
Masks a set of characters.
The function of anti-quotation marks is different from the above three kinds of symbols. He does not have the ability to block special characters. But through him.
Pass the result of a command to another command.
Such as:
contents= ' ls ' (bash/pdksh)
Set contents = ' ls ' (tcsh)
Test command in a 4.shell program
In Bash/pdksh, the command test is used to evaluate the value of a conditional expression. They are often in conditional statements and loops
The statement is used to determine whether certain conditions are met.
Syntax format for the test command:
Test expression
Or
[Expression]
In the test command, you can use many of the shell's internal operators. These operators are described below:
(1) string operator for evaluating string expressions
Test Command | Meaning
-----------------------------------------
STR1 = str2 | Returns True when Str1 and str2 are in the same phase
str1! = str2| Returns True when STR1 is different from str2
Str | Returns True when STR is not a null character
-N-Str | Returns True when the length of STR is greater than 0 o'clock
-Z Str | Returns True when the length of STR is 0 o'clock
-----------------------------------------
(2) Integer operators have functions similar to the character operators. It's just that their operation is for integers.
Test-expression | Meaning
---------------------------------------------
Int1-eq int2| returns True when Int1 equals Int2
Int1-ge int2| Returns True when INT1 is greater than/equal to Int2
Int1-le int2| Returns True when Int1 is less than/equal to Int2
INT1-GT int2| Returns True when Int1 is greater than int2
Int1-ne int2| Returns True when Int1 is not equal to Int2
-----------------------------------------
(3) Operators for file operations, they can check: whether the file exists, file type, etc.
Test-expression | Meaning
------------------------------------------------
-D File | Returns True when file is a directory
-F File | Returns True when file is a normal
-R File | Returns True when file is a read
-S File | Returns True when the filename is longer than 0 o'clock
-W File | Returns True when file is a writable
-X File | Returns True when file is an executable file
------------------------------------------------
(4) The Shell's logical operator is used to modify/concatenate an expression containing integers, strings, and file operators
Test-expression | Meaning
----------------------------------------------------------
! Expr | Returns True when the value of expr is false
Expr1-a expr2| returns True when the EXPR1,EXPR2 value is True
Expr1-o expr2| Returns True when the value of EXPR1,EXPR2 has at least one true
-----------------------------------------------------------
Attention:
The TCSH shell does not use the test command, but the expression in tcsh can also assume the same function. tcsh
Expressions that support expressions in C are the same. Typically used in the IF and while commands.
TCSH-expression | Meaning
-------------------------------------------------------
Int1 <= Int2 | Returns True when INT1 is less than/equal to Int2
Int1 >= Int2 | Returns True when INT1 is greater than/equal to Int2
Int1 < Int2 | Returns True when INT1 is less than int2
Int1 > Int2 | Returns True when INT1 is greater than int2
STR1 = = STR2 | Returns True when STR1 is the same as str2
Str1! = str2 | Returns True when STR1 is different from str2
-R File | Returns True when file is a readable
-W File | Returns True when file is a writable
-X File | Returns True when file is an executable file
-E File | Returns True when file exists
-O File | Returns True when the file owner is the current user
-Z File | Returns True when file length is 0 o'clock
-F File | Returns True when file is a normal
-D File | Returns True when file is a directory
EXP1 | | Exp2 | Returns True when the value of EXP1 and EXP2 is at least one true
EXP1 && Exp2 | Returns True when the value of EXP1 and EXP2 is the same as true
! Exp | returns TRUE when EXP has a value of false
5. Conditional statements
As with other high-level language programs, the branch and loop control structures are often used in complex shell programs.
Bash,pdksh and tcsh each have two different forms of conditional statements: The IF statement and the case statement.
(1) If statement
Syntax format:
Bash/pdksh usage:
if [expression1]
Then
Commands1
elif [Expression2]
Commands2
Else
Commands3
If
TCSH usage:
if (expression1) then
Commands1
else if (expression2) then
Commands2
Else
Commands3
endif
Meaning: When the expression1 condition is true, the shell executes the COMMANDS1 command after then;
When the condition of expression1 is false and the condition of expression2 is true, the shell executes
Commands2 command, when the condition value of expression1 and Expressin2 is false, the shell executes
The COMMANDS3 command. The IF statement ends with his anti-write fi.
(2) Case statement
The case statement requires the shell to compare a string s with a set of string patterns P1,p2,..., pn, when S and
When a pattern pi wants to match, it executes the corresponding part of the program/command. Character in Shell Case statement
A pattern can contain wildcards such as *.
Syntax format:
Bash/pdksh usage:
Case string1 in
STR1)
COMMANDS1;;
STR2)
COMMANDS2;;
*)
COMMANDS3;;
Esac
TCSH usage:
Switch (string1)
Case STR1:
Statements1
Breaksw
Case STR2:
Statements2
Breaksw
Default
Statements3
Breaksw
Endsw
Meaning: The shell compares string string1 to string patterns str1 and str2 respectively. If string1 and str1
Match, then
The shell executes the COMMANDS1 command/statement; if String11 and str2 match, the Shell executes COMMANDS2
The command/
Statement. Otherwise the shell executes the COMMANDS3 program/command. Each branch of the program/command is
With a total of two
Semicolon (;;) End.
6. Looping statements
The loop statement is used when certain actions need to be repeated.
(1) For statement
You know that in many programming languages the for statement is the most common. In the shell is no exception. The For statement requires the shell
Will contain
A set of commands in this statement executes a certain number of times consecutively.
Syntax format:
Bash/pdksh
Usage 1:
For var1 in list
Do
Commands
Done
Meaning: In this for statement, which corresponds to each value in the list, the shell executes a commands represented by a
Group command.
In each execution of the entire loop, the variable var1 will take the different values in the list.
Usage 2:
For var1
Do
Setatements
Done
Meaning: In this for statement, the shell performs a statements representation for each item in the variable var1, respectively.
A set of
command. When using this form of statement, the shell thinks that the VAR1 variable contains all the positional variables, and the position
Variables in
The value of the command line parameter that holds the program. That is, he is equivalent to the following form:
For var1 in "[email protected]"
Do
Statements
Done
TCSH usage:
There is no for this word in tcsh, and the same function as the For statement is the foreach statement
foreach Name (list)
Commands
End
Example:
for file; Bash/pdksh
Do
TR A-Z a-z< $file >file.caps
Done
#; tcsh
foreach file ($ *)
TR A-Z a-z< $file > $file. Caps
End
(2) While statement
The while statement is another circular statement provided by the shell. The while statement specifies an expression and a set of commands. This
A
Statement causes the shell to repeatedly execute a set of commands until the value of the expression is false.
Syntax format:
while expression; bash
Do
Statements
Done
while (expression); tcsh
Statements
End
Example:
count=1; bash
While [-N "$ *"] * * *
Do
echo "This is a parameter number $count $"
Shift
Count= ' expr $count + 1 '
Done
Set count = 1; tcsh
while ("$ *"!) = "")
echo "This is a parameter number $count $"
Shift
Set count = ' expr $count + 1 '
End
The function of the shift command in a statement is to pass all command-line arguments in turn.
(3) until statement
The until and while statements have similar syntax formatting and functionality, unlike the value of expression in the while
True,
The shell executes the command group, and the shell executes the set of commands when the value of expression is false in until.
Syntax format:
Until expression
Do
Commands
Done
Example:
Count=1
Until [-Z "$ *"] * * *
echo "This is a parameter number $count $"
Shift
Count= ' expr $count + 1 '
Done
Note the above example with a * * number. Expression in while:-n string, he means when string does not
is empty
String, the value of the expression is true; the expression in until:-Z string, his meaning is when the string
is empty
String, the value of the expression is true. This shows that the two programs set the conditional expression exactly the opposite.
(4) Shift statement
Both bash and TCSH support the shift command. Shift places the command-line arguments that are stored in the position variable, and then left-handed
. For example
The current value of the position variable is:
$1=file1 $2=file2 $3=file3
Once the shift command is executed, the value of the position variable is:
$1=file2 $2=file3
You can also specify the number of times the position variable is transferred in the shift command, such as:
Shift N
Example:
While ["$"]
Do
If ["$" = "-i"] Then
Infile= "$"
Shift 2
else if ["$" = "-O"] Then
Outfile= "$"
Shift 2
Else
echo "Rogram $ does not recognize option $"
Fi
Done
TR A-Z a-z< $infile > $outfile
(5) SELECT statement
The SELECT statement is a unique looping statement provided by Pdksh. He is different from the Loop statement described earlier. He doesn't
Is
Evaluates a conditional expression repeatedly and determines whether to execute a set of commands based on the value of the expression. The function of Select is
Auto-
Generates a simple text menu.
Syntax format:
Select menu [In List_of_items]
Do
Commands
Done
Meaning: When executing a SELECT statement, Pdksh creates a single member of each column in the List_of_items, respectively.
A menu
Options. List_of_items can be a variable that contains multiple options, or it can be directly listed in the program.
A set of options
If the statement does not provide a list_of_items,select statement, the position variable is used as the
List_of_items.
Example:
Select MenuItem in Pick1 Pick2 Pick3
Do
echo "Is you sure-want to pick $menuitem"
Read res; receives input from the user and stores the input values in a specific variable.
if [$res = "Y"-o $res = "Y"]
Then
break; To exit a looping statement such as While,for,select
Fi
Done
(6) Repeat statement
The repeat statement is a unique loop statement provided by TCSH. Use the repeat command to require the shell to execute a command
Must
The number of times.
Syntax format:
Repeat Count command
such as
foreach num ($ *)
Repeat $num echo-n "*"
echo ""
End
Functions in 7.shell
The shell allows users to define their own functions. Functions are an important structure in a high-level language. A function in the shell is in C or
Person Other
functions defined in the language. The main advantage of using a function is that it has a
Facilitate the organization
The entire program. In bash, a function has the following syntax:
FName () {
Shell Comands
}
Once you have defined the functions, you need to call them in your program. The format of the calling function in bash:
fname [Parm1 parm2 parm3 ...]
When you call a function, you can pass any number of arguments to the function. The function considers these parameters to be the command-line arguments that hold his
Number of
Position variable.
Example:
This program defines 4 functions:
Upper (): Converts the letters in the file passed to him to uppercase, and holds the file with an. Out at the end of the same name
In.
Lower (): Converts the letters in the file passed to him into lowercase, and stores the file with the. Out at the end of the same name
In.
Print (): Outputs the contents of the file passed to him.
Usage_error (): The Help information for the output program.
The main module of the program is a case condition statement, which determines the function that the program will complete according to the first parameter in the command line.
, and call the corresponding
function to complete this function.
Upper () {
Shift
For I
Do
TR a-a A-z<$!>$1.out
RM $
MV $1.out $
Shift
Done }
Lower () {
Shift
For I
Do
TR A-Z a-z<$1>$1.out
RM $
MV $1.out $
Shift
Done }
Print () {
Shift
For I
Do
LPR $
Shift
Done }
Usage_error () {
echo "$ syntax is $"
echo ""
echo "where option is one of the following"
echo "P--to Print frame Files"
echo "U--to Save As uppercase"
echo "l--to Save As lowercase";}
Case $ in
P | -p) Print [email protected];;
u | -u) Upper [email protected];;
l | -l) Lower [email protected];;
*) Usage_error;;
Esac
----------------------------------------------------------
Summarize
The use of shell programming is an important means to improve the efficiency of system management, learn the shell and understand the basic command of the system
and management
How to use the tool is equally important!
Report:
Commands that are commonly used in A.bash
Command | Meaning
-----------------------------------------------------------
alias | set command Alias
Bg | A suspended process is executed in the background
CD | Change the user's current directory
Exit | Terminate a Shell
Export | The variable and its current value, which is used as the argument for this command, are available in the child process of the currently running shell
See
FC | Edit the current command line History list
FG | Let a suspended process execute in the foreground
Help | shows you helpful information for bash internal commands
History | Displays a certain number of command lines that have been recently entered
Kill | Terminates a process
PWD | Displays the user's current working directory
Unalias | Remove command-line aliases
-------------------------------------------------
System variables commonly used in B.bash
Variables | Meaning
-------------------------------------------------
Editor,fcedit | Default text editor for the FC command of Bash
Histfile | Specifies the name of the most recently entered command line file
Histsize | Specifies the size of the command line history file
HOME | The current user's host directory
Oldpwd | The previous directory used by the user
Path | Specifies the paths that bash searches for when searching for executable files
PS1 | Display the first level hint symbol in the command line environment
PS2 | Show second level hint symbol in command line environment
PWD | User's current working directory
SECONDS | Run time (in seconds) of the currently running bash process
This article is from the "lake and Laughter" blog, please make sure to keep this source http://xuexuhui.blog.51cto.com/9647696/1653576
Shell day-to-day app win