Linux_ (4) Shell programming (bottom)

Source: Internet
Author: User
Tags case statement closing tag echo command logical operators

Five, Shell Process Control
1. A heavy Branch
If statement syntax format:
If condition
Then
Command1
Fi
The FI at the end is the if inverted.
Write a line:
if condition; Then Command1; Fi

2. Two branches
If ELSE syntax format:
If condition
Then
Command1
Else
Command
Fi

3. Multiple branches
If else-if else syntax format:
If Condition1
Then
Command1
Elif Condition2
Then
Command2
Else
CommandN
Fi

4. Example
Determine if two variables are equal:
#!/bin/bash
a=10
B=20
if [$a = = $b]
Then
echo "a equals B"
elif [$a-gt $b]
Then
echo "A greater than B"
elif [$a-lt $b]
Then
echo "A is less than B"
Else
echo "No conditions met."
Fi

The 5.if Else statement is used in conjunction with the test command
#!/bin/bash
NUM1=$[2*3]
NUM2=$[1+5]
if test $[num1]-eq $[num2]
Then
Echo ' Two numbers equal! '
Else
Echo ' Two numbers are not equal! '
Fi

6.for Cycle
The general format for A for loop is:
For Var in item1 item2 ... itemn
Do
Command1
Done
Write a line:
For Var in item1 item2 ... itemn; Do Command1; Command2. Done;
When the value of the variable is in the list, the For loop executes all commands once, using the variable name to get the current value in the list.
The command can be any valid shell command and statement.
The in list can contain replacements, strings, and file names.
The in list is optional, if it is not used, the For loop uses the command-line positional parameters.

Example 1:
Sequentially prints the numbers in the current list:
For I in 1 2 3 4 5
Do
echo "The value is: $i"
Done

Example 2:
Characters in the sequential output string:
For str ' A string '
Do
Echo $str
Done
Output Result:
This is a string

7.while statements
The while loop is used to continuously execute a series of commands,
Also used to read data from the input file;
Commands are usually test conditions.
The format is:
While condition
Do
Command
Done

The following is a basic while loop, and the test condition is:
If int is less than or equal to 5, then the condition returns True.
int starts at 0, and each time the loop is processed, int plus 1.
Run the above script, return the number 1 to 5, and then terminate.
#!/bin/sh
Int=1
while (($int <=5))
Do
Echo $int
Let "int++"
Done
Using the Bash let command, it is used to execute one or more expressions,
You do not need to add $ to the variable calculation to represent the variable, specifically: Bash let command.

The while loop can be used to read keyboard information.
In the following example, the input information is set to the variable film, ending the loop by <Ctrl-D>.
Echo ' Press <CTRL-D> exit '
Echo-n ' Enter your favorite website name: '
While read film
Do
echo "Yes! $film is a good website "
Done

8. Infinite Loops
Syntax format:
While:
Do
Command
Done
Or
While True
Do
Command
Done
Or
for ((;;))
For ((i=1;i<=5;i++))

i++
++i
I+=i


9.until Cycle
The Until loop executes a series of commands until the condition is true.
The Until loop and the while loop are just the opposite of the processing mode.
The general while loop is better than the until loop, but at some point-and only in rare cases-the until loop is more useful.
Until syntax format:
Until condition
Do
Command
Done
The condition can be any test condition, and the test takes place at the end of the loop, so the loop executes at least once-note this.
Example:
#! /bin/bash
int=5;
until [$int = = 10]
Do
Let "int++";
echo "$int";
Done

10.case selection
The Shell Case statement is a multi-select statement.
A case statement can be used to match a value with a pattern, and if the match succeeds, the matching command is executed.
The case statement is in the following format:
Case value in
Mode 1)
Command1
;;
Mode 2)
Command1
;;
Esac

The value must be followed by the word in, and each pattern must end with a closing parenthesis.
The value can be either a variable or a constant. After the match discovery value conforms to a pattern, all commands begin to execute until;;.
The value will detect each pattern that matches.
Once the pattern matches, the other mode is no longer resumed after the corresponding command is executed.
If there is no matching pattern, use an asterisk * to capture the value and then execute the subsequent command.
ESAC is the case in turn as the closing tag, with the right parenthesis for each case branch,
--use two semicolons to indicate a break.

Example 1:
The following script prompts you to enter 1 to 4 to match each pattern:
Echo ' Enter a number from 1 to 4: '
Echo ' The number you entered is: '
Read Anum
Case $aNum in
1) echo ' You have chosen 1 '
;;
2) echo ' You have chosen 2 '
;;
3) echo ' You have chosen 3 '
;;
4) echo ' You have chosen 4 '
;;
*) echo ' You did not enter a number between 1 and 4 '
;;
Esac

11. Jump out of the loop
During the loop, sometimes it is necessary to force the loop to break out when the loop end condition is not reached.
The shell uses two commands to implement this function: Break and continue.
11.1 Break Command
The break command allows you to jump out of all loops (all loops after the execution is terminated).
The script enters a dead loop until the user enters a number greater than 5.
To jump out of this loop and return to the shell prompt, you need to use the break command.
#!/bin/bash
While:
Do
Echo-n "Enter a number from 1 to 5:"
Read Anum
Case $aNum in
1|2|3|4|5) echo "The number you entered is $aNum!"
;;
*) echo "The number you entered is not between 1 and 5!" Game Over "
Break
;;
Esac
Done

11.2 Continue
Does not jump out of all loops, just jumps out of the current loop.
To modify the above example:
#!/bin/bash
int=5;
until [$int = = 10]
Do
Let "int++";
if [$int = = 8]
Then
Continue
Fi
echo "$int";
Done


Six, Shell array
1. Defining arrays
Multiple values can be stored in an array.
The Bash Shell supports only one-dimensional arrays (which do not support multidimensional arrays) and does not need to define the size of the array when initializing.
The subscript of an array element starts with 0.
The Shell array is represented by parentheses, and the elements are separated by a "space" symbol, with the following syntax:
Array_name= (value1 ... valuen)

Example:
#!/bin/bash
my_array= (A B "C" D)

You can also use subscripts to define arrays:
Array_name[0]=value0
Array_name[1]=value1
Array_name[2]=value2

2. Reading an array
To read an element in an array to take advantage of subscripts, the subscript can be an integer or an arithmetic expression whose value should be greater than or equal to 0.
The general format for reading array element values is:
${array_name[index]}
Example:
#!/bin/bash
my_array= (A B "C" D)
echo "first element: ${my_array[0]}"
echo "second element: ${my_array[1]}"
echo "The third element is: ${my_array[2]}"
echo "fourth element: ${my_array[3]}"

3. Get all the elements in the array
Use @ or * to get all the elements in the array,
#!/bin/bash
My_array[0]=a
My_array[1]=b
My_array[2]=c
My_array[3]=d
echo "Elements of array: ${my_array[*]}"
echo "Elements of array: ${my_array[@]}"

The elements of the array are: A B C D
The elements of the array are: A B C D

4. #获取数组的长度
The method of getting the length of the array is the same as getting the length of the string, using "#"
For example:
#!/bin/bash
My_array[0]=a
My_array[1]=b
My_array[2]=c
My_array[3]=d
echo "array element number: ${#my_array [*]}"
echo "array element number: ${#my_array [@]}"


5. Assigning values to array elements using variables
A=1
my_array= ($A B C D)
echo "first element: ${my_array[0]}"
echo "second element: ${my_array[1]}"
echo "The third element is: ${my_array[2]}"
echo "fourth element: ${my_array[3]}"
The output is:
The first element is: 1 The second element is: b The third element is: c The fourth element is: D

6. When the array element value is obtained from an array element index, the array subscript can be a variable.
#!/bin/bash
Arr= (a B c d)
For ((i=0;i<${#arr [*]};i++))
Do
Echo ${arr[i]}
Done

Seven, Shell echo command
The echo command is used for the output of a string.
Command format: Echo string

1. Display Normal string:
echo "It is a test"

2. Show escape characters
echo "\" It is a test\ ""

3. Display variables
The read command reads a row from the standard input and assigns the value of each field in the input row to the shell variable
#!/bin/sh
Read name
echo "$name It is a test"
#由name变量接收标准输入
Called./echo.sh
OK #标准输入

4. Show line breaks
Echo-e "ok! \ n "#-E Open escape
echo "It it a test"

5. Show No Line break
#!/bin/sh
Echo-e "ok! \c "#-E Open escape \c no Line break
echo "It is a test"

6. Show results directed to file
echo "It is a test" > myfile

7. Single quotes: output strings As-is, without escaping or taking variables
echo ' $name \ '

8. Show command Execution results
echo ' Date ' #结果将显示当前日期

String summary of 9.echo output
Can I reference a variable | Can I reference escape characters | Can I reference text format characters (such as: line breaks, tab characters)
Single Quotes | No | No | Yes
Double Quotes | can | can | Yes
No quotation marks | can | can | Whether

Example:
#! /bin/bash
Your_name= "LW";
echo $your _name;
echo "\" ";
echo \ ";
Read name;
echo "$name is a test";
Echo-e "Ok!\c";
echo ' $name \ \ n ';
Echo ' Date '
Date
Aa.

Eight, printf command
The printf command mimics the C-language printf () function, so scripting with printf is better than using echo portability.
printf uses reference text or space-delimited parameters, which can be used outside of the format string in printf.
You can also specify the width of the string, the left and right alignment, and so on.
Default printf does not wrap, and you can manually add \ n line breaks.

Syntax for the 1.printf command:
printf format-string [arguments ...]
Parameter description:
Format-string: A string that controls the format
Arguments: Parameter list.
Example:
$ echo "Hello, Shell"
$ printf "Hello, shell\n"

2.%d%s%c%f format override:
D:decimal Decimal integer--the corresponding positional parameter must be a decimal integer, otherwise error!
S:string string--the corresponding position parameter must be a string or character type, otherwise error!
C:char character--the corresponding position parameter must be a string or character type (only one character output), otherwise error!
F:float floating Point-the corresponding position parameter must be a digital type, otherwise error!

Example 1:
$ printf "%d%s%c\n" 1 "abc" "DEF"
Example 2:
#!/bin/bash
printf "%-10s%-8s%-4s\n" name sex weight kg
printf "%-10s%-8s%-4.2f\n" Guo Jingnan 66.1234
printf "%-10s%-8s%-4.2f\n" Yang over male 48.6543
printf "%-10s%-8s%-4.2f\n" Guoff female 47.9876

%-10s refers to a width of 10 characters (-for left-aligned, no to right-aligned),
Any character will be displayed in the 10 character justifies characters,
If it's not enough, it's automatically populated with spaces, and the content will all be displayed.
%-4.2F refers to the format of decimals, where. 2 refers to 2 decimal places reserved.

3. More examples:
#!/bin/bash
# format-string can have single quotes, double quotes, no quotes
printf "%d%s\n" 1 "ABC"
printf '%d%s\n ' 1 "ABC"
printf%s abcdef
# The format specifies only one parameter, but the extra parameter is still output in that format, format-string is reused
printf%s ABC def
printf "%s\n" ABC def
printf "%s%s%s\n" a b c D e F g h i J
# If there is no arguments, then%s is replaced with NULL,%d replaces with 0
printf "%s and%d \ n"

Escape sequence of 4.printf
\a warning character, usually the bel character of ASCII
\b Back
\c suppresses (does not display) the newline character at any end of the output (only valid in the parameter string under the%B Format indicator control),
Furthermore, any characters left in the argument, any subsequent arguments, and any characters left in the format string are ignored
\f Page Change (formfeed)
\ nthe line break
\ r Enter (carriage return)
\ t Horizontal tab
\v Vertical Tab
\ \ A literal backslash character
The \DDD represents a 1 to 3-digit octal value character. Valid only in format strings
\0DDD represents 1 to 3-bit octal value characters
Example:
$ printf "A string, no processing:<%s>\n" "A\NB"
Output: A string, no processing:<a\nb>
$ printf "A string, no processing:<%b>\n" "A\NB"
Output: A string, no processing:<a
B>

Nine, Test command
The test command is used to check if a condition is true, and it can be tested in three aspects of numeric, character, and file.

1. Numerical test
-eq equals True
-ne is not equal to true
-GT is greater than true
-ge is true if it is greater than or equal
-lt is less than true
-le is less than or equal to true

Example:
#!/bin/bash
num1=100;
num2=100;
if test $[num1]-eq $[num2]
Then
Echo ' num1=num2 '
Else
Echo ' num1!=num2 '
Fi

#!/bin/bash
num1=100;
num2=100;
If [$num 1-eq $num 2]
Then
Echo ' num1=num2 '
Else
Echo ' num1!=num2 '
Fi

2. String test
= Equals is True
! = is not equal is true
-Z String string is true if the length is zero
-N String string is true if the length is nonzero

Example:
#!/bin/bash
num1= "Oracle"
Num2= "ORCL"
if test $num 1 = $num 2
Then
Echo ' num1=num2 '
Else
Echo ' num1!=num2 '
Fi

#!/bin/bash
num1= "Oracle"
Num2= "ORCL"
if [$num 1 = $num 2]
Then
Echo ' num1=num2 '
Else
Echo ' num1!=num2 '
Fi

3. File Testing
-e File name True if the file exists
-r file name True if the file exists and is readable
-W file name True if the file exists and is writable
-X file name if file exists and executable is true
-S file name True if the file exists and has at least one character
-d file name if the file exists and is true for the directory
-f filename If file exists and is normal file true
-C file name True if the file exists and is a character-specific file
-B file name True if file exists and is a block special file

Example:
Cd/bin

If Test-e./bash
Then
Echo ' file already exists! '
Else
Echo ' file does not exist! '
Fi

4. With (-a), or (-O), non (!) Three logical operators
With (-a), or (-O), non (!) Three logical operators are used to connect multiple test conditions.
Its priority is: "!" Highest, "-a" followed, "-O" the lowest.
For example:
Cd/bin
If Test-e./notfile-o-E./bash
Then
Echo ' has a file present! '
Else
Echo ' Two files are not present '
Fi

Ten, Shell functions
User-defined functions, which can be called randomly in shell scripts.
1. The function is defined in the following format:
[Function] funname [()]
{
Action
[Return int;]
}
Description
Can be defined with a function fun () or directly fun (), without any parameters.
Parameters returned, can be displayed plus: return returns, if not added, will run the result as the last command, as the return value.
return followed by value N (0-255)

2. No parameter, no return value function
Define the function first, and then call the function (using the function name to invoke the function).
#!/bin/bash
Demofun () {
echo "This is a function of shell"
}
echo "-----function starts execution-----"
Demofun
echo "-----function completed-----"

3. Functions with a return statement:
function return value after calling this function through $? To get.
#!/bin/bash
Funwithreturn () {
echo "Please input A:"
Read a
echo "Please input B:"
Read B
Return $ (($a + $b))
}
Funwithreturn;
Sum=$?;
echo "$sum"

4. Function parameters
In the shell, arguments can be passed to a function when it is called.
Within the body of the function, the value of the parameter is obtained by $n form.
For example, $ $ represents the first argument, and the second argument ...
Output all parameters as a string 1 2 3 4 5 6 7 8 9 34 73!
Note that the $ $ cannot get the tenth parameter, and the tenth parameter requires ${10}. When n>=10, you need to use ${n} to get the parameters.
#!/bin/bash
Funwithparam () {
echo "The first parameter is $!"
echo "The second parameter is $!"
echo "The tenth parameter is $ A!"
echo "Tenth parameter is ${10}!"
echo "11th parameter is ${11}!"
echo "The total number of parameters is $#!"
echo "Output all parameters as a string $*!"
}
Funwithparam 1 2 3 4 5 6 7 8 9 34 73

#!/bin/bash
Funsum () {
Return $ (($1+$2))
}
Funsum 4 6;
Sum=$?;
echo "$sum"

5. Special characters are used to process parameters:
$# the number of arguments passed to the script
$* displays all parameters passed to the script in a single string
[Email protected] is the same as $*, but is used with quotation marks and returns each parameter in quotation marks.

$$ the current process ID number for the script to run
$! ID number of the last process running in the background
$-shows the current options that the shell uses, as is the SET command function.
$? Displays the exit status of the last command. 0 means there is no error, and any other value indicates an error.

Xi. Shell file contains
The shell can contain external scripts,
This allows you to use some common code as a standalone file.
The Shell file contains the following syntax format:
. FileName # Note number (.) There is a space in the middle of the file
Or
SOURCE filename

Example:
The SUM function is sum.sh as a separate file, and the contained file sum.sh does not require executable permissions.
#!/bin/bash
Sum () {
Return $ (($1+$2))
}
Minus () {
Return $ (($1-$2))
}
Cheng () {
Return $ (($1*$2))
}
Chu () {
Return $ (($1/$2))
}

#!/bin/bash
. ./sum.sh
# source./test1.sh
Sum 4 6;
Value=$?;
echo "4+6= $value"
Minus 10 6;
Value=$?;
echo "10-3= $value"
Cheng 2 5
Value=$?;
echo "2*5= $value"
Chu 9 5
Value=$?;
echo "9/5= $value"

Homework:
Conditional Statement Practice
1. Enter three numbers and print the maximum number of three

Looping statement Exercises
1.Shell script Implementation, 1-10 cumulative and
2.Shell script implementation, 1-100 even and
3,shell script implementation, two array of cumulative and

Linux_ (4) Shell programming (bottom)

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.