Linux_ (3) Shell programming (top)

Source: Internet
Author: User
Tags arithmetic arithmetic operators bit set echo command logical operators readable

First, Shell introduction
The shell is a program written in C that is a bridge for users to use Linux.
The shell is both a command language and a programming language.
A Shell is an application that provides an interface through which users access the service of the operating system kernel.

1.Shell Script
Shell script, a scripting program written for the shell.
What is a scripting language?
Scripting language is the language that teaches a computer to do something like a screenplay,
This type of program can be modified with a text editor, which does not need to be compiled, and is usually interpreted as running.

2.Shell Environment
There are many types of Shell in Linux, common:
Bourne Shell (/usr/bin/sh or/bin/sh)
Bourne Again Shell (/bin/bash)
C Shell (/USR/BIN/CSH)
K Shell (/usr/bin/ksh)
Shell for Root (/sbin/sh)
......
Bash (Bourne Again Shell) is the most widely used and the default shell for most Linux systems in your daily work.
Under normal circumstances, the Bourne shell and the Bourne Again Shell are not distinguished,
So, like #!/bin/sh, it can also be changed to #!/bin/bash.
#! Tells the system that the program specified after the path is the shell that interprets this script file.

3. First shell script
Open a text editor (you can use the Vi/vim command to create a file),
Create a new file hello.sh with the extension sh (sh for Shell), and the extension does not affect script execution.
Cat > Hello.sh <<!
Instance
#!/bin/bash
echo "Hello world!"
#! is a contract tag that tells the system what interpreter the script needs to execute, even if it uses a Shell.
The echo command is used to output text to a window.

4. There are two ways to run a Shell script:
4.1 As an executable program
Save the above code as hello.sh and CD to the appropriate directory:
chmod u+x./hello.sh #使脚本具有执行权限
./hello.sh #执行脚本
Note that it must be written in./hello.sh, not hello.sh, as well as running other binary programs,
Direct write Hello.sh,linux system will go to the PATH to find there is not called hello.sh,
And only/bin,/sbin,/usr/bin,/usr/sbin, etc in PATH,
The current directory is usually not in PATH, so writing hello.sh will not find the command,
Use the./hello.sh to tell the system that it is looking in the current directory.

4.2 As interpreter parameter
This works by running the interpreter directly, whose parameters are the file names of the shell scripts, such as:
/bin/sh hello.sh
The script that runs this way does not need to specify the interpreter information in the first line, and it is useless to write.

Second, shell variables
1. Defining variables
Your_name= "LW"
Note: There can be no spaces between the variable name and the equals sign.
The name of the variable must be named according to the following rules:
The first character must be a letter (a-z,a-z).
You can use an underscore (_) without spaces in the middle.
Punctuation cannot be used.
You can't use the keywords in bash (you can see the reserved keywords using the help command).

2. Using variables
With a defined variable, just precede the variable name with a dollar sign, such as:
Your_name= "LW"
Echo $your _name
Example:
Cat > Your_name.sh <<!
#!/bin/bash
Your_name= "LW"
Echo $your _name

chmod u+x./your_name.sh #使脚本具有执行权限
./your_name.sh #执行脚本

The curly braces outside the variable name are optional and add no lines, and curly braces are used to help the interpreter identify the bounds of the variable.
Echo ${your_name}
A defined variable that can be reused:
#!/bin/bash
Your_name= "LW"
Echo ${your_name}
Your_name= "Alibaba"
Echo ${your_name}

3. read-only variables
Use the readonly command to define a variable as a read-only variable, and the value of a read-only variable cannot be changed.
Attempt to change read-only variable, result error: your_name: read-only variable
#!/bin/bash
Your_name= "LW"
Echo ${your_name}
ReadOnly your_name
Your_name= "Alibaba"
Echo ${your_name}

4. Deleting variables
Use the unset command to delete a variable. Grammar:
Unset variable_name
The variable cannot be used again after it has been deleted. The unset command cannot delete a read-only variable.

#!/bin/bash
Your_name= "LW"
Echo ${your_name}
#readonly your_name
Unset your_name
Echo ${your_name}

5. Variable type
When you run the shell, there are three different variables:
5.1 Local Variables
A local variable is defined in a script or command and is valid only in the current shell instance.
Other shell-initiated programs cannot access local variables.
5.2 Environment variables
All programs, including shell-initiated programs, can access environment variables,
Some programs require environment variables to keep them running properly.
Shell scripts can also define environment variables when necessary.
5.3 Shell variables
Shell variables are special variables that are set by the shell program.
Some of the shell variables are environment variables, some of them are local variables,
These variables guarantee the shell's normal operation.

6.Shell string
Strings are the most common and useful data types (numbers and strings) in shell programming.
Strings can be in single or double quotes, or without quotation marks.
6.1 Single quotation marks
Your_name= ' LW '
Single-Quote String restrictions:
Any character in a single quotation mark is output as is,
The variable in the single-quote string is not valid;
Single quotation marks cannot appear in single quote strings (not after using escape characters for single quotes).

6.2 Double Quotes
Advantages of double quotes:
You can have variables in double quotes.
Escape characters can appear in double quotes
Cat > Your_name3.sh <<!
#!/bin/bash
Your_name= ' LW '
echo "hello,${your_name}!"
#echo "Hello, \" $your _name\ "! \ n "

6.3 Stitching Strings
6.4 # Get string length
CP your_name3.sh your_name4.sh

#!/bin/bash
Your_name= "LW"
String=hello
echo $string $your _name
echo ${#string}
echo ${#your_name}

6.5: Extract substring
4 characters starting from the 2nd character of the string:
#!/bin/bash
string= "Hello lw!"
echo ${string:1:4} # Output Ello

6.6 Finding substrings
Find the location of the character "E":
#!/bin/bash
string= "Hello lw!"
echo ' expr index ' $string ' e ' # output 2
Note: the "'" in the above script is an anti-quote instead of a single quotation mark "'".
CP your_name4.sh your_name5.sh
VI your_name5.sh
#!/bin/bash
string= "Hello lw!"
Echo ${string:1:4}
echo ' expr index ' $string ' e '

7.Shell comments
Lines that begin with "#" are comments, which are ignored by the interpreter.
Each line plus a # number can be commented on one line;
There is no multiline comment in sh, you can enclose this piece of code for comment in a pair of curly braces.
Defined as a function, there is no place to call this function, the code will not be executed, to achieve the same effect as the annotation.

8. Eight ways to intercept a string:
Suppose there is a variable var=http://www.aaa.com/123.htm
8.1 Start with the first few characters on the left and the number of characters
Echo ${var:0:5}
0 represents the first character on the left and 5 indicates the total number of characters.
The result is: http:

8.2 Start from the first few characters on the left, until the end.
Echo ${var:7}
7 means that the 8th character on the left begins, until the end.
The result is: www.aaa.com/123.htm

8.3 Starting with the first character on the right and the number of characters
Echo ${var:0-7:3}
0-7 means that the seventh character starts at the right, and 3 indicates the number of characters.
The result is: 123

8.4 Start with the first few characters on the right, until the end.
Echo ${var:0-7}
The expression starts at the seventh character on the right and continues to the end.
Result is: 123.htm
Note: (The first character on the left is denoted by 0, and the first character on the right is denoted by 0-1)

#, # # means to delete from the left.
A # Indicates the deletion from the left to the first specified character;
Two # indicates the deletion from the left to the last specified character.
%, percent% means delete from right.
A% represents the deletion from the right to the first specified character;
Two% indicates the deletion from the right to the last specified character.
The deletion includes the specified character itself.

8.5 # Intercept, delete the left character, and leave the right character.
Echo ${var#*//}
where Var is the variable name and the # is an operator, *//indicates that the first//number and all characters on the left are deleted from the left.
Delete http://
Echo ${var#*/}
The result is:/www.aaa.com/123.htm

8.6 # # Intercept, delete the left character and leave the right character.
Echo ${var##*/}
##*/indicates that the last (rightmost) one/number and all characters to the left are deleted from the left.
That is, delete http://www.aaa.com/
The result is 123.htm.

8.7% Intercept, delete right character, leave left character
Echo ${var%/*}
%/* indicates that the first/second and right characters are deleted from the right.
The result is: http://www.aaa.com

8.8-percent intercept, delete the right character, leave the left character
Echo ${var%%/*}
%%/* indicates that the last (leftmost) one/number and right character are deleted from the right.
The result is: http:

Three, Shell pass parameters
1. Passing parameters
When executing a Shell script, parameters are passed to the script, and the format of the parameters obtained in the script is: $n.
n represents a number, 1 is the first argument to execute the script, 2 is the second argument to execute the script, and so on ...
CP your_name.sh parameter.sh
#!/bin/bash
echo "Hello $";
Call:./parameter.sh LW

2. Parameter handling
$# the number of arguments passed to the script
$* displays all parameters passed to the script in a single string, outputting all parameters in the form of "$ $ ... $n".
[Email protected] is the same as $*, but uses quotes (such as "[email protected]") and returns each parameter "$" and "$" in quotation marks ... "$n".
$* and [email protected] Difference:
The same point: all parameters are referenced.
Different points: only in double quotes.
Suppose you wrote three parameters 1, 2, 3 when the script was run,
"*" is equivalent to "1 2 3" (passing a parameter),
The "@" is equivalent to "1" "2" "3" (three parameters are passed).
CP prameter.sh prameter2.sh
#!/bin/bash
echo "$";
echo "$";
echo "$#";
Echo $*;
For i in "$*"; Do
Echo $i
Done
echo "[email protected]";
For i in "[email protected]"; Do
Echo $i
Done
Call:./prameter2.sh LW 1123 NULL

Four, Shell operators
The shell operators are divided into 6 classes, including:
Arithmetic operators
Relational operators
Boolean operator
logical operators
String operators
File Test Operators

Native bash does not support simple math operations, but can be done with the expr command.
Expr is an expression evaluation tool that uses it to perform evaluation operations on expressions.
For example, two numbers are added (note the use of anti-quotes ' instead of single quotes '):
#!/bin/bash
Val= ' Expr 2 + 2 '
echo "Sum of two numbers: $val"
Two points Note:
There is a space between the expression and the operator, for example, the 2 + 2 must be written.
The complete expression is to be contained, note that this character is not a common single quote, below the ESC key.

1. Arithmetic operators
The following table lists the commonly used arithmetic operators, assuming that variable A is 10 and variable B is 20:
+ addition ' expr $a + $b ' result is 30.
-Subtraction ' expr $a-$b ' result is-10.
* multiply ' expr $a \* $b ' result is 200. Multiplication sign (*) must be in front of the backslash (\) to achieve multiplication
/Division ' expr $b/$a ' result is 2.
% "Expr $b% $a ' result is 0.
The expr syntax for the shell in MAC is: $ (expression), where "*" in the expression does not need to escape the symbol "\".

= Assignment A= $b assigns the value of variable B to a.
= = Equal. Used to compare two numbers, the same returns true. [$a = = $b] returns FALSE.
! = is not equal. Used to compare two numbers, and returns true if they are different. [$a! = $b] Returns TRUE.
NOTE: Conditional expressions are placed between square brackets and have spaces,
For example: [$a = = $b] is wrong and must be written as [$a = = $b].

An example of an arithmetic operator is as follows:
#!/bin/bash
a=10;
b=20;
Val= ' expr $a + $b ';
echo "A + B: $val";

Val= ' expr $a-$b ';
echo "A-B: $val";

Val= ' expr $a \* $b ';
echo "A * B: $val";

Val= ' expr $b/$a ';
echo "b/a: $val";

val= ' expr $b% $a ';
echo "B% A: $val";

if [$a = = $b]
Then
echo "a equals B";
Elfi [$a! = $b]
Then
echo "A is not equal to B"
Fi


#!/bin/bash
a=10;
b=20;
echo "a+b= $ ((a+b))";
echo "a-b= $ ((a))";
echo "a*b= $ ((a*b))";
echo "B/a= $ ((b/a))";
echo "a%3= $ ((a%3))";

2. Relational operators
Relational operators only support numbers, and strings are not supported unless the value of the string is a number.
The following table lists the commonly used relational operators, assuming that variable A is 10 and variable B is 20:
-eq = = Detects whether two numbers are equal and returns true for equality. [$a-eq $b] returns false.
-ne! = Detects whether two numbers are not equal and returns true. [$a-ne $b] returns TRUE.
-GT > (Result error) detects if the number on the left is greater than the right, and returns true if it is. [$a-gt $b] returns false.
-lt < (result error) detects if the number on the left is less than the right and, if so, returns True. [$a-lt $b] returns TRUE.
-ge >= (Error) detects if the number on the left is greater than or equal to the right, and if so, returns True. [$a-ge $b] returns false.
-le <= (Error) detects if the left number is less than or equal to the right, and returns true if it is. [$a-le $b] returns TRUE.

EQ is equal equals
NE is not equal is not equal to
GT is greater than greater than
Lt is less than than
GE is greater than or equal greater than or equal to
Le is less than or equal smaller than or equal to

The relational operator instance is as follows:
#!/bin/bash
a=10;
b=20;
If [$a-eq $b]
Then
echo "$a-eq $b: a equals B"
Else
echo "$a-eq $b: A is not equal to B"
Fi
If [$a-ne $b]
Then
echo "$a-ne $b: A is not equal to B"
Else
echo "$a-ne $b: a equals B"
Fi
If [$a-gt $b]
Then
echo "$a-gt $b: a greater than B"
Else
echo "$a-gt $b: A is not much more than B"
Fi
If [$a-lt $b]
Then
echo "$a-lt $b: a less than B"
Else
echo "$a-lt $b: A is not less than B"
Fi
If [$a-ge $b]
Then
echo "$a-ge $b: A is greater than or equal to B"
Else
echo "$a-ge $b: a less than B"
Fi
If [$a-le $b]
Then
echo "$a-le $b: A is less than or equal to B"
Else
echo "$a-le $b: a greater than B"
Fi

3. Boolean operators
The following table lists the commonly used Boolean operators, assuming that variable A is 10 and variable B is 20:
! Non-operation, the expression is true returns False, otherwise true. [! false] returns TRUE.
-O or operation, which returns true if an expression is true. [$a-lt 20-o $b-GT 100] returns TRUE.
-A with operation, two expressions are true to return true. [$a-lt 20-a $b-GT 100] returns FALSE.

Examples of Boolean operators are as follows:
#!/bin/bash
a=10
B=20
if [$a! = $b]
Then
echo "$a! = $b: A is not equal to B"
Else
echo "$a! = $b: a equals B"
Fi
If [$a-lt 100-a $b-gt 15]
Then
echo "$a less than 100 and $b greater than 15: Returns True"
Else
echo "$a less than 100 and $b greater than 15: returns false"
Fi
If [$a-lt 100-o $b-GT 100]
Then
echo "$a less than 100 or $b greater than 100: Returns True"
Else
echo "$a less than 100 or $b greater than 100: returns false"
Fi
If [$a-lt 5-o $b-GT 100]
Then
echo "$a less than 5 or $b greater than 100: Returns True"
Else
echo "$a less than 5 or $b greater than 100: returns false"
Fi

4. Logical operators
The following is a description of the Shell's logical operators, assuming that variable A is 10 and variable B is 20:
&& logical AND [[$a-lt && $b-GT 100]] returns false
|| Logical OR [[$a-lt | | $b-GT 100]] returns True

Examples of logical operators are:
#!/bin/bash
a=10
B=20
if [[$a-lt && $b-GT 100]]
Then
echo "Return True"
Else
echo "return False"
Fi

if [[$a-lt | | $b-GT 100]]
Then
echo "Return True"
Else
echo "return False"
Fi

5. String operators
The following table lists the commonly used string operators, assuming that variable a is "ABC" and Variable B is "EFG":
= detects whether two strings are equal and returns true for equality. [$a = $b] returns FALSE.
! = detects whether two strings are not equal and returns true. [$a! = $b] Returns TRUE.
-Z detects if the string length is 0 and returns true for 0. [-Z $a] returns false.
-N detects whether the string length is not 0 and does not return true for 0. [-N $a] returns true.
STR detects whether the string is not empty and returns true if it is not null. [$a] returns TRUE.

Examples of string operators are as follows:
#!/bin/bash
A= "ABC"
b= "EFG"
if [$a = $b]
Then
echo "$a = $b: a equals B"
Else
echo "$a = $b: A is not equal to B"
Fi
if [$a! = $b]
Then
echo "$a! = $b: A is not equal to B"
Else
echo "$a! = $b: a equals B"
Fi
If [-Z $a]
Then
echo "-Z $a: string length 0"
Else
echo "-Z $a: string length is not 0"
Fi
If [-N $a]
Then
echo "-N $a: string length not 0"
Else
echo "-N $a: string length 0"
Fi
If [$a]
Then
echo "$a: String not empty"
Else
echo "$a: string is empty"
Fi

6. File Test Operators
File test operators are used to detect various properties of Unix files.
Attribute detection is described as follows:
The-B file detects whether the files are block device files and, if so, returns True. [-B $file] returns FALSE.
The-C file detects whether the files are character device files and, if so, returns True. [-C $file] returns false.
The-D file detects whether the files are directories and, if so, returns True. [-D $file] returns false.
The-F file detects whether files are normal files (neither directories nor device files), and if so, returns True. [-F $file] returns TRUE.
The-P file detects if the files are named pipes and, if so, returns True. [-P $file] returns false.

The-R file detects whether the files are readable and, if so, returns True. [-R $file] returns TRUE.
The-W file detects whether the files are writable and, if so, returns True. [-W $file] returns TRUE.
The-X file detects whether files can be executed and, if so, returns True. [-X $file] returns TRUE.
-S file to detect whether the files are empty (the file size is greater than 0) and not NULL to return TRUE. [-S $file] returns TRUE.
The-e file detects whether files (including directories) exist and, if so, returns True. [-e $file] returns TRUE.
The-G file detects if the SGID bit is set and returns True if it is. [-G $file] returns false.
The-K file detects whether the files have a sticky bit set (Sticky bit), and returns True if it is. [-K $file] returns false.
-U file detects whether the file has a SUID bit set and returns True if it is. [-U $file] returns false.
The variable file represents the document "/var/www/a.txt" and has rwx permissions.
The following code will detect various properties of the file:
#!/bin/bash
File= "/home/lw/a.txt"
If [-R $file]
Then
echo "File readable"
Else
echo "File not readable"
Fi
If [w $file]
Then
echo "File writable"
Else
echo "File not writable"
Fi
If [-X $file]
Then
echo "File Executable"
Else
echo "File not executable"
Fi
If [-f $file]
Then
echo "File as normal file"
Else
echo "File as special file"
Fi
If [-D $file]
Then
echo "File is a directory"
Else
echo "File is not a directory"
Fi
If [-s $file]
Then
echo "File is not empty"
Else
echo "File is empty"
Fi
If [-e $file]
Then
echo "File exists"
Else
echo "file does not exist"
Fi

Linux_ (3) Shell programming (top)

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.