Basic Introduction to simple shell for Linux Programming

Source: Internet
Author: User
Tags case statement

Http://www.3800hk.com/Article/ OS /Linux/bckflu/2005-08-06/Article_37229_2.html

Code :--------------------------------------------------------------------------------

1. Create and run Shell programs
What is a shell program? Simply put, a shell program is a program that contains several rows.
Shell or Linux Command file.
Like programming in advanced languages, writing a shell program requires a text editor, such as VI.
In the text editing environment, enter shell/Linux Command lines according to shell syntax rules to form a complete
Program file.
There are three methods to execute shell program files
(1) # chmod + X file
(2) # sh File
(3) #. File
When writing a shell, the first line must specify the shell that the system needs to explain your shell program, such :#! /Bin/bash,
#! /Bin/CSH,/bin/tcsh, or #! /Bin/pdksh.
2. Variables in Shell
(1) Common System Variables
$ #: Number of command line parameters for saving programs
$? : Save the return code of the previous command.
$0: Save the program name
$ *: Saves all input command line parameters in the form of ("$1 $2 ...")
$ @: Saves all input command line parameters in the form of ("$1" $2 "...)
(2) define variables
The shell language is a non-type interpreted language. Unlike C ++/Java programming, variables must be declared in advance.
Variable values are actually defined variables.
In all the shells supported by Linux, you can assign values to variables using the value assignment symbol (=.
For example:
ABC = 9 (Bash/pdksh cannot leave spaces on both sides of the equal sign)
Set abc = 9 (tcsh/CSH)
Because shell program variables are non-typed, you can use the same variable to store characters and
Integer.
For example:
Name = ABC (Bash/pdksh)
Set Name = ABC (tcsh)
After assigning a value to a variable, you only need to add $ to reference the variable.
For example:
Echo $ ABC
(3) location variable
When you run a shell program that supports multiple command line parameters, the values of these variables are stored in the location variables respectively.
The first parameter is stored in location variable 1, the second parameter is stored in location variable 2, and so on..., shell retains
These variables do not allow users to define them in an out-of-order manner. The same variables are referenced with the $ symbol.

3. How to use quotation marks in Shell
Shell uses quotation marks (single quotes/double quotes) and backslash ("/") to shield some special characters from the shell interpreter.
Reverse quotation marks (") have special significance for shell.
For example:
ABC = "how are you" (Bash/pdksh)
Set abc = "how are you" (tcsh)
In this command line, how are you strings composed of three words are assigned to the variable ABC as a whole.
ABC1 = '@ LOGNAME, how are you! '(Bash/pdksh)
Set ABC1 = '$ LOGNAME, how are you! '(Tcsh)
Abc2 = "$ LOGNAME, how are you! "(Bash/pdksh)
Set abc2 = "$ LOGNAME, how are you! "(Tcsh)
The LOGNAME variable is the shell variable that saves the current user name. Assume that the current value is: Wang. After two commands are executed,
The content of ABC1 is: $ LOGNAME, how are you !. The content of abc2 is: Wang, how are you !.
Like single quotes, The backslash can also block all special characters. However, it can only block one character at a time.
A group of characters.
The anti-quotation mark function is different from the above three symbols. It does not have the function of shielding special characters. However, you can use
The running result of a command is passed to another command.
For example:
Contents = 'LS' (Bash/pdksh)
Set contents = 'LS' (tcsh)
4. Test command in shell Program
In bash/pdksh, the command test is used to calculate the value of a conditional expression.
The statement is used to determine whether certain conditions are met.
Syntax format of the test command:
Test expression
Or
[Expression]

Many internal shell operators can be used in the test command. These operators are described as follows:
(1) The string operator is used to calculate the string expression.
Test command | meaning
-----------------------------------------
Str1 = str2 | returns true if str1 and str2 are the same
Str1! = Str2 | returns true if str1 and str2 are different
STR | returns true if STR is not a null character.
-N str | returns true if the STR length is greater than 0.
-Z str | returns true if the STR length is 0.
-----------------------------------------
(2) integer operators have functions similar to character operators, but their operations are for integers.
Test expression | meaning
---------------------------------------------
Int1-EQ int2 | returns true if int1 is equal to int2
Int1-ge int2 | returns true if int1 is greater than/equal to int2
Int1-Le int2 | returns true if int1 is smaller than/equal to int2
Int1-GT int2 | returns true if int1 is greater than int2
Int1-ne int2 | returns true if int1 is not equal to int2
-----------------------------------------
(3) operators used for file operations. They can check whether a file exists and the file type.
Test expression | meaning
------------------------------------------------
-D file | returns true if file is a directory.
-F file | returns true if file is a normal file.
-R file | returns true if the file is an engraved file.
-S file | returns true if the file length is greater than 0.
-W file | returns true if the file is a writable file.
-X file | returns true if file is an executable file.
------------------------------------------------
(4) Shell logical operators are used to modify/connect expressions that contain integers, strings, and file operators.
Test expression | meaning
----------------------------------------------------------
! Expr | returns true if the value of expr is false.
Expr1-A expr2 | returns true if both expr1 and expr2 are true.
Expr1-O expr2 | returns true if at least one value of expr1 and expr2 is true.
-----------------------------------------------------------
Note:
Tcsh shell does not use the test command, but the expressions in tcsh can share the same functions. tcsh
The supported expressions are the same in C. They are usually used in the IF and while commands.
Tcsh expression | meaning
-------------------------------------------------------
Int1 <= int2 | returns true if int1 is smaller than/equal to int2
Int1> = int2 | returns true if int1 is greater than/equal to int2
Int1 <int2 | returns true if int1 is smaller than int2
Int1> int2 | if int1 is greater than int2, true is returned.
Str1 = str2 | returns true if str1 and str2 are the same
Str1! = Str2 | returns true if str1 and str2 are different
-R file | returns true if file is a readable file.
-W file | returns true if the file is a writable file.
-X file | returns true if file is an executable file.
-E file | returns true if the file exists.
-O file | returns true if the file owner is the current user.
-Z file | returns true if the file length is 0.
-F file | returns true if file is a normal file.
-D file | returns true if file is a directory.
Exp1 | exp2 | returns true if at least one of the values of exp1 and exp2 is true.
Exp1 & exp2 | returns true if the values of exp1 and exp2 are both true.
! Exp | returns true if the exp value is false.
5. conditional statements
Like other advanced language programs, branch and loop control structures are often used in complex Shell programs,
Bash, pdksh, and tcsh both have two different forms of conditional statements: If statement and 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 condition of expression1 is true, shell executes the commands1 command after then. When
When the condition of expression1 is false and the condition of expression2 is true, shell runs
Commands2 command; when the condition values of expression1 and expressin2 are both false, shell executes
The commands3 command. If statement ends with its anti-write fi.

(2) case statement
The case statement requires shell to compare a string s with a group of string modes P1, P2,..., Pn, when S and
When you want to match a pattern Pi, execute the corresponding characters in the case statement of the Program/command. Shell.
This mode can contain wildcard characters such.
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: Shell compares string1 with str1 and str2. If string1 matches str1
Shell executes the commands1 command/statement. If string11 and str2 match, shell executes the commands2 command/
Statement. Otherwise, shell will execute the commands3 Program/command. The program/command of each branch must start with two
Semicolon (;) ends.

6. Loop statements
Loop statements are used when repeated operations are required.

(1) For statement
We know that for statements are the most common in many programming languages. They are no exception in shell. For statements require shell to include
A group of commands in this statement are executed continuously for a certain number of times.
Syntax format:
Bash/pdksh
Usage 1:
For var1 in list
Do
Commands
Done
Meaning: In this for statement, corresponding to each value in the list, shell will execute a group of commands represented by commands once.
In each execution of the entire loop, the variable var1 will take different values in the list accordingly.
Usage 2:
For var1
Do
Setatements
Done
Meaning: In this for statement, shell executes one set of statements for each item in the variable var1.
Command. When statements in this form are used, shell considers that the var1 variable contains all the location variables, while the location variable contains
The command line parameter value of the program is stored. That is, it is equivalent to the following form:
For var1 in "$ @"
Do
Statements
Done

Tcsh usage:
The word for does not exist in tcsh. The foreach statement has the same function as the for 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 loop statement provided by shell. The while statement specifies an expression and a group of commands.
Statement causes shell to execute a group of commands until the expression value 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 $1"
Shift
Count = 'expr $ count + 1'
Done

Set COUNT = 1; tcsh
While ("$ *"! = "")
Echo "this is a parameter number $ count $1"
Shift
Set COUNT = 'expr $ count + 1'
End

In a statement, the shift command is used to transmit all command line parameters to the left.

(3) until statement
The until and while statements have similar syntax formats and functions. The difference is that when the expression value in while is true,
The shell executes the command group, while the shell executes the command group only when the expression value in until is false.
Syntax format:
Until expression
Do
Commands
Done
Example:
Count = 1
Until [-z "$ *"] ***
Echo "this is a parameter number $ count $1"
Shift
Count = 'expr $ count + 1'
Done
Note: In the preceding example, the expression *** in the while clause is-N string, which means that when the string is not empty
String, the expression value is true; In the until expression:-Z string, its meaning is when string is empty
String, the expression value is true. It can be seen that the two programs set the conditional expression exactly the opposite.

(4) shift statement
Bash and tcsh both support the shift command. Shift will store the command line parameters in the location variable and pass them to the left in sequence. For example
The current location variable value is:
$1 = file1 $2 = file2 $3 = file3
After a shift command is executed, the value of the location variable is:
$1 = file2 $2 = file3
You can also specify the number of times the location variable is transferred in the shift command, for example:
Shift n
Example:
While ["$1"]
Do
If ["$1" = "-I"] Then
Infile = "$2"
Shift 2
Else if ["$1" = "-o"] Then
OUTFILE = "$2"
Shift 2
Else
Echo "program $0 does not recognize option $1"
Fi
Done
Tr A-Z A-Z <$ infile> $ OUTFILE

(5) select statement
The SELECT statement is a unique loop statement provided by pdksh. It is different from the previous loop statement. It is not
Calculate a conditional expression repeatedly and determine whether to execute a group of commands based on the value of the expression. The select function is automatic.
Generate a simple text menu.
Syntax format:
Select menu [IN list_of_items]
Do
Commands
Done
Meaning: When executing a SELECT statement, pdksh creates a menu for each member in list_of_items.
Option. list_of_items can be either a variable containing multiple options or a set of options directly listed in the program
. If the list_of_items statement is not provided, the SELECT statement uses the location variable as list_of_items.
Example:
Select menuitem in pick1 pick2 pick3
Do
Echo "are you sure you want to pick $ menuitem"
Read res; receives user input and stores the input value in a specific variable.
If [$ res = "Y"-o $ res = "Y"]
Then
Break; used to exit loop statements such as while, for, and select.
Fi
Done
(6) Repeat statement
The repeat statement is a unique loop statement provided by tcsh. Using the repeat Command requires shell to execute certain
Number of times.
Syntax format:
Repeat count command
For example;
Foreach num ($ *)
Repeat $ num echo-n "*"
Echo ""
End

7. Functions in Shell
Shell allows users to define their own functions. functions are important structures in advanced languages. Functions in shell are in C or other
The functions defined in the language are the same. Compared with writing a program one line at the beginning, the main benefit of using a function is to facilitate the organization.
The syntax format of a function in Bash is as follows:
Fname (){
Shell comands
}
After defining a function, you need to call the format of the function called in. bash in the program:
Fname [parm1 parm2 parm3. ..]
When calling a function, you can pass any number of parameters to the function. The function regards these parameters as storing their command line parameters.
Location variable.
Example:
This program defines four functions:
Upper (): converts the letters in the file passed to him into uppercase letters, and saves them to the file with the name ending with. Out.
Lower (): converts the letters in the file passed to him into lowercase, and saves them to the file with the name ending with. Out.
Print (): output the content of the file passed to him.
Usage_error (): output program help information.
The main module of the program is a case Condition Statement. Based on the first parameter in the command line, it determines the function to be completed by the program and calls the corresponding
Function to complete this function.
Upper (){
Shift
For I
Do
Tr A-A A-Z <$!> $ 1.out
Rm $1
MV $ 1.out $1
Shift
Done ;}
Lower (){
Shift
For I
Do
Tr A-Z A-z <$1> $ 1.out
Rm $1
MV $ 1.out $1
Shift
Done ;}
Print (){
Shift
For I
Do
LPR $1
Shift
Done ;}
Usage_error (){
Echo "$1 syntax is $1"
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 $1 in
P |-p) Print $ @;;
U |-u) Upper $ @;;
L |-l) lower $ @;;
*) Usage_error $0 ;;
Esac

------------------------------------------------------------------------------
Summary
Using shell programming is an important way to improve the efficiency of system management. Learn shell well and understand basic system commands and management.
The usage of the tool is equally important!

Appendix:
A. Common commands in bash
Command | meaning
-------------------------------------------------------------------------------
Alias | set command alias
BG | execute a suspended process in the background
CD | change the current directory of the user
Exit | terminate a shell.
Export | make the variable and its current value used as the parameter of this command visible in the sub-process of the currently running Shell
FC | edit the current command line history list
FG | run a suspended process on the foreground
Help | display the help information of bash Internal commands
History | displays a certain number of command lines recently entered.
Kill | terminate a process
PWD | displays the user's current working directory
Unalias | delete a command line alias
--------------------------------------------------------------------------------

B. Common System variables in bash
Variable | meaning
-------------------------------------------------------------------------------
Editor, fcedit | default text editor for Bash FC commands
Histfile | specifies the name of the recently entered command line file.
Histsize | specifies the size of the history file of the command line.
Home | home directory of the current user
Oldpwd | previous directory used by the user
Path | specifies the path that Bash searches for executable files.
PS1 | displays the first level of hint in the command line Environment
PS2 | the second-level prompt symbol is displayed in the command line environment.
PWD | current working directory of the user
Seconds | the running time of the currently running bash process (in seconds)

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: info-contact@alibabacloud.com 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.