Linux Shell programming notes

Source: Internet
Author: User
Tags constant definition

Contents
1. Shell Introduction
1.1. What is shell?
1.2. Shell Classification
2. Shell syntax
2.1. Define Variables
2.2. Variable type
2.2.1. Character Set Variables
2.2.2. Digital constant definition
2.2.3. Array
2.2.4. System Variables
2.3. Operators and expressions
2.3.1. Operator
2.3.2. String expression (IF)
2.3.3. String operations
2.3.4. numeric expression
2.3.5. Compound condition expression
2.4. Process Control
2.4.1. conditional transfer: If Condition Statement
2.4.2. Select the statement case
2.4.3. Cyclic statements
2.5. Use of functions in Shell
2.5.1. function declaration
2.5.2. Local Variables
2.5.3. shell script file Parameters
2.5.4. Function Parameters
2.6. Type Variable
2.6.1. Declare declares type variables
2.7. Interaction functions in Shell files
2.8. Escape (\)

Linux Shell Study Notes

Shell Introduction What is Shell

the Linux Shell serves as the shell of the operating system and provides users with interfaces for using the operating system. It is a general term for the command language, command interpretation Program , and programming language.
shell is the interface program between the user and the Linux kernel. If you think of the Linux kernel as the center of a sphere, shell is centered around the outer kernel. When commands are passed from shell or other programs to Linux, the kernel will respond accordingly.
shell is a command language interpreter. It has its own built-in shell command set and can also be called by other applications in the system. The commands entered by the user at the prompt are explained by Shell and then passed to the Linux core.
some commands, such as changing the working directory command CD, are included in the shell. There are also some commands, such as Copy command CP and move command RM, which are separate programs in a directory in the file system. For users, there is no need to worry about whether a command is built inside shell or a separate program.
shell first checks whether the command is an internal command. If not, it checks whether it is an application (the application here can be a Linux utility, such as LS and RM, it can also be a purchased commercial program, such as XV, or a free software, such as Emacs ). Then shell searches for these applications in the search path (the search path is a list of directories where executable programs can be found ). If the entered command is not an internal command and the executable file is not found in the path, an error message is displayed. If the command is successfully found, the internal command or application will be decomposed into system calls and passed to the Linux kernel.
another important feature of shell is that it is an interpreted programming language. shell programming language supports most program elements that can be seen in high-level languages, such as functions, variables, arrays, and program control structures. Shell programming language is easy to learn. Any command that can be typed in a prompt can be placed in an executable shell program.
when a common user successfully logs on, the system runs a program called shell. The shell process provides a command line prompt. As the default value (BASH is the default shell in turbolinux), "$" is used as a prompt for common users and "#" is used as a prompt for Super Users (Root.

Once a shell prompt appears, you can enter the command name and the parameters required by the command. Shell will execute these commands. If a command takes a long time to run, or a large amount of output is generated on the screen, you can press Ctrl + C on the keyboard to interrupt it (stop it before it ends normally ).
When you are about to end the Login Dialog process, you can enter the logout command, the exit command, or the file terminator (EOF) (press Ctrl + D to complete the logon.

Shell Classification

There are multiple types of Shell in Linux, the most common of which are Bourne shell (SH), c shell (CSH), and Korn shell (Ksh ). Each of the three shells has its own advantages and disadvantages. The Bourne shell is the original shell used by UNIX and can be used on every UNIX. Bourne shell is excellent in shell programming, but it is inferior to several other shells in dealing with user interactions.The default shell in Linux is the Bourne again shell, which is an extension of the Bourne shell, bash for short,It is completely backward compatible with the Bourne shell and adds and enhances many features based on the Bourne shell. Bash is placed in/bin/bash. It has many features, such as command completion, command editing, and command history table, it also contains many advantages of C shell and Korn shell, flexible and powerful programming interfaces, and friendly user interfaces.
C shell is a shell that is more suitable for programming than the Bourne shell. Its syntax is similar to that of C. Linux provides tcsh for people who like to use C shell. Tcsh is an extension of C shell. Tcsh includes command line editing, programmable word completion, spelling correction, historical command replacement, Job control, and syntax similar to C language. It is not only compatible with bash shell as a prompt, it also provides more prompt parameters than bash shell.
The Korn shell combines the advantages of C shell and Bourne shell and is fully compatible with the Bourne shell. Linux provides pdksh (Ksh extension), which supports task control and can be suspended on the command line, executed in the background, awakened, or terminated.

Shell syntax definition Variables

Shell is a non-type interpreted language. Unlike C ++/Java programming, variables need to be declared in advance. assigning values to a variable actually defines variables.
Because shell program variables are non-typed, you can use the same variable to store characters and numbers.
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)
For example:
Name = ABC (Bash/pdksh)
After assigning a value to a variable, you only need to add $ to reference the variable.
For example:
Echo $ ABC

Variable type character set variable

The double quotation marks are used to declare character set variables.
For example:
ABC = "how are you" (assign the character set how are you to ABC)
Echo $ ABC
Output result: How are you
Reference System variable assignment
For example:
ABC = "$ LOGNAME, how are you"; ($ LOGNAME stores the user name for system logon)
Echo $ ABC
Output result: Root, how are you
String Addition
ABC = "how are you" "root"
Echo $ ABC
Output result: How are you root

Numeric constant definition

Decimal: Write numbers directly
For example, a = 12 # A is in decimal 12.
: Add 0 to the front
For example, a = 012 # A is octal 12
16 forbidden: Add 0x before the number
For example, a = 0x12 # A is hexadecimal 12

Array

The array subscript starts with zero;
Array usage
For example:
Arr1 = (1 2 3 4 5) # define the array arr1 and initialize 5 values
Echo ${arr1 [0]} # print the nth variable value in the array
Arr1 [0] = 6 # assign the first value in the array to 6
Echo ${arr1 [0]} # print the nth variable value in the array

System Variables

System variables are environment variables, which can be called directly in the operating system after being defined. for different users, all the system variables are different;
Use Export to declare system variables, for example:
Export varname = "system Var" # declare varname as a system variable;
You can directly access varname at the operating system prompt.
For example: # echo $ varname
Execution result: System VaR

Operators and expression Operators

Arithmetic Operators
+ Addition
-Subtraction
* Multiplication
/Division
** Power Operation
Let "z = 5 ** 3"
Echo "z = $ Z" # z = 125.
% Modulo
+ = Add or equal to (add a variable through a constant)
For example, let "Var + = 5" # var will increase by 5 based on its own value.
-= Subtraction equals
* = Multiplication equals
For example, let "Var * = 4"
/= Division equals
% = Modulo value assignment,
Expr or let expressions are often used for arithmetic operations.

Logical operators
| Logical or
& Logic and

String expression (IF)

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.

For example, file B. Sh is as follows:
#! /Bin/bash
A1 = "ABC"
B1 = "ABC"
C1 = "ABCDE"
If ["$ A1" = "$ B1"]
Then
Echo "a1 = B1"
Fi
If ["$ A1 "! = "$ C1"]
Then
Echo "A1 <> C1"
Fi
If [-n "$ A1"]
Then
Echo "$ A1 length> 0"
Fi
Output result:
A1 = b1
A1 <> C1
ABC length> 0

String operation

Returns the length of the string. Usage: expr length para
# Para represents a string variable
String truncation. Usage: $ {para: X1: X2}
# Para represents the string variable parameter, x1 represents the truncation position, and x2 represents the truncation length, which can be omitted
How to delete a substring: {string # substring}
# Delete the first substring from the string;
Substring replacement,
$ {String/substring/replacement}
Use $ replacement to replace the first matched $ substring.
$ {String // substring/replacement}
Use $ replacement to replace all matched $ substring.

For example, file B. Sh
#! /Bin/bash
String1 = teststring
Expr length $ string1 # String Length
Echo $ {string1: 0} # output string
Echo $ {string1: 1} # output substring, starting from the second character to the end of the string
Echo $ {string1: 1: 3} # output 1st to 3 Characters
Echo ${string1 # test} # Delete the test substring from the string
Echo $ {string1/test/replace} # Replace the substring test in the string with replace
Output result:
10
Teststring
Eststring
EST
String

Numeric expression
    1. Judgment statement

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

Example: file B. Sh as follows
#! /Bin/bash
Int1 = 3
Int2 = 4
If [$ int1-EQ $ int2]
Then
Echo "int1 = int2"
Else
Echo "int1 <> int2"
Fi

Execution result:
Int1 <> int2

Compound condition expression

Instance: such as file B. Sh
#! /Bin/bash
Int1 = 3
Int2 = 4
If [$ int1-ge 1] & [$ int2-le 7]
Then
Echo "int1> = 1 and int2 <= 7"
Fi
If [$ int1-ge 1] | [$ int2-LE 1]
Then
Echo "int1> = 1 or int2 <= 1"
Fi

Execution result:
Int1> = 1 and int2 <= 7
Int1> = 1 or int2 <= 1

Process control condition transfer: If Condition Statement

Syntax:
If [condition]
Then # qualified
Expression
Else # non-conforming
Expression
FI # End Condition
Detailed examples are described in each instance in this document.

Select statement case
    1. Select a comparison operator and select a composite condition expression from the following conditions.

Such as file: B. Sh
#! /Bin/bash
A1 = 2;
Case $ A1 in
1)
Echo "a1 = 1 ";;
2)
Echo "a1 = 2 ";;
Esac

Execution result: A1 = 2

Loop statement
    1. The following lists the usage of three common loop statements. The three programs implement the same function.
  1. For Loop
  1. While Loop
  1. Until Loop

Instance: B. Sh
#! /Bin/bash
For I in 1 2 3 4 5
Do
Echo "$ I"
Done &

  1.  

Instance: B. Sh
#! /Bin/bash
I = 1
While [$ I-le 5]
Do
Let "I + = 1"
Echo "$ I"
Done

Instance: B. Sh
#! /Bin/bash
I = 0
Until [$ I-EQ 5]
Do
Let "I + = 1"
Echo "$ I"
Done

  1. Output result

1
2
3
4
5

  1. Output result

1
2
3
4
5

  1. Output result

1
2
3
4
5

Use the function declaration in Shell

Function declaration:
Function_name () # declare a function
{
Command # The main body of the function, the command to be executed;
}

Example: B. Sh
#! /Bin/bash
Testfunction () # Function Description and processing process
{
Echo "this is a test function"
}
Testfunction # function call

Execution result: this is a test function

Local variable

The local variables in the function are declared using local. The scope of the variables is within the function. After the function is executed, the local variables are deleted;
Example B. Sh
#! /Bin/bash
ABC = 112233 # declare the global variable ABC
Localpara () # define a function
{
Local abc = 123 # define the local variable ABC. Note that the above ABC is distinguished.
Echo "local para ABC is $ ABC" # output local variables
}
Localpara # Call the function and output the local variable ABC
Echo "ABC is $ ABC" # output global variable ABC, variable value not changed
Execution result:
Local para ABC is 123
ABC is 112233

Parameters of the shell script file

File Parameters
The following describes how to use parameters in a shell script:
./B. Sh start # Start is the first parameter.

Call method:
./B. Sh test1 output: This is runpara1
./B. Sh Test2 output: This is runpara2

Special file Parameters
$0 script program name
$ N the nth parameter of the program file
$ * All parameters of the program file
$ # Number of program file Parameters
$ PID of program File Execution

See the following script file.
#! /Bin/bash
Runpara1 () # function declaration
{
Echo "this is runpara1"
}

Runpara2 () # function declaration
{
Echo "this is runpara2"
}
If [$ #-GT 0]
Then
Echo "Para count> 0"
Fi

Case $1 in #$1 indicates the value of the first parameter
Test1) # If the parameter is test1, run the runpara1 function.
Runpara1
;;
Test2)
Runpara2
;;
Esac

Function Parameters

File B. Sh as follows
#! /Bin/bash
Testfunction () # declare a function
{
If [-z "$1"] # determine whether a function has a parameter ($1)
Then
Echo "No para in function" # No parameter Processing
Else
Echo "function's paraname is" $1 "" # parameter Processing
Fi
}
Testfunction start # executes the function. The function parameter is start.
Execution result: function's paraname is start

Type Variable declare declares Type Variable

Declare-r abc = "test string" # declare that ABC is a read-only type
Declare-I int1 # declare int1 as an integer
Declare-A arr1 # declare arr1 as an array variable
Declare-f function name (optional) # When a function name exists, only the name in the file is the definition of the function written. If no function name exists, the declaration of all functions is listed.

See the following example B. sh:
#! /Bin/bash
Declare-r abc = "test declare" # declare the read-only variable ABC
Echo "Echo $ ABC"
ABC = "Read Only" # An error will be prompted because ABC is a read-only variable.
Echo "Echo $ ABC" # print the ABC variable, or "test declare" does not change

Declare-I int1 # declare the integer variable int1
Int1 = 12;
Int1 = "test string" # assign a value to an integer as a string, error
Echo "$ int1"
Int1 = int1/3 # integer variables can directly use the operator/
Echo "$ int1"

Func1 () # declare the function func1
{
Echo "test function"
}
Func2 () # declare the function func2
{
Echo "test function"
}
Declare-F # Show All functions
Declare-F func1 # display function func1

The execution result of the file is as follows:
Echo test declare
./B. sh: ABC: readonly variable # error message about Read-Only variables
Echo test declare
./B. sh: test string: syntax error in expression (error token is "string") # variable Type Error
12
4 # The result is 12/3.
Declare-F func1 () # Show All functions
{
Echo "test function"
}
Declare-F func2 ()
{
Echo "test function"
}
Func1 () # display function func1
{
Echo "test function"
}

Interaction in shell files

The program must judge the characters entered by the user and then perform the corresponding operation.
The following file is B. Sh.
# The function completed by the program is to determine the name entered by the user. If the name entered by the user is not Zhangwei, the system will continue to prompt the input. if the user has entered Zhangwei, the system will prompt the welcome character and exit the program;
#! /Bin/bash
While:
Do
Echo-n "Please input you name:" # prompt for user input
Read line # Read user input data
If ["$ line" = "Zhangwei"] # judge user input data
Then
Echo "Welcome $ line" # display welcome information
Exit
Fi
Done

 

Escape (\)

Escape is a method to reference a single character. If an escape character (\) is placed at the front of a character with special meanings, it indicates that shell has no special meaning.
Special meanings of specific escape characters (used in ECHO and SED)
\ N line feed
\ R press ENTER
\ T Tab key
\ V vertical tab (vertical tab), check the CTL-K of the front side
\ B backspace: Check the CTL-H of the front side.
\ A "alert" (such as beep or flash)
Convert \ 0xx to octal ASCII decoding, which is equivalent to oxx
Instance, use the Escape Character "\"
Check the file B. Sh.
#! /Bin/bash
Echo "\ v" # print string "\ v ."
Echo-e "\ v" # Print four vertical tabs
Echo $ '\ v \ V' # Print four vertical tabs
Echo-e "\ 101" # print out a, because a is the ASCII of octal 101
Echo \ Z # output Z
Echo '\ Z' # output \ Z
Echo \ Z # output \ Z

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.