Shell Study Notes

Source: Internet
Author: User
Tags bitwise operators

Shell scripting is an interpreted language;

The essence of shell scripts is an ordered set of shell commands;

1. Basic shell programming process

1) create a shell file

2) grant executable permissions to chmod A + x filename

3) execute the shell file./filename

2 shell Variables

1) User-Defined variables

Naming rules are based on the naming rules in C language;

Variable Assignment Method: first write the variable name, then =, followed by a new value, with no spaces in the middle. When you want to retrieve the value of a variable, add the "$" symbol.

WhenWhen there is a space in the value assignment content, please add double quotation marks; You can use unset + variable name to cancel variable assignment.

For example:

Definition: Name = value (quote when using a value with spaces)

Access: $ name

Example: fruit = Apple

$ Echo $ fruit (Result: Apple)

$ Echo fruit (Result: Fruit)

The Bourne shell only supports scalar, And the Korn shell supports arrays.

Array creation: name [Index] = value array access: $ {name [Index]}

Read-Only variable: readonly name

Delete variable: unset name

Local variables (only available in the current shell instance), environment variables (can be used by any shell sub-process), shell variables (required for proper running, such as PWD, path, home, etc ).

Export environment variable: Export Name

Variables in the form of $ {Variable} may be seen. The extra curly braces on both sides of the variable name are usually used to help identify the variable name after $.

In addition, pay attention to the usage of reverse quotation marks in shell:

Reverse quotation marks·Is in the wave number ~ The same key position. The back quotes allow you to assign the shell command output to the variable, which is one of the most important components in Script Programming.

For example: test = 'date', shell runs the command in the back quotes and outputs it to the variable test.

For example, in the script, obtain the current date through reverse quotation marks and use it to generate a unique file name:

#!/bin/bash#date.shtoday=`date +%y%m%d`ls /home > log.$today


Note that there must be a space 'date + % Y % m % d' after the date command'
Chmod U + x date. Sh
./Date. Sh the file log.130710 is generated at this time.
Redirect input> is used here. In addition, there is a redirection input <, and>, indicating to append the output to the end of the file.
2) location variable
$0:
$1,... $9, including the first to ninth command line parameters
$ # Number of command inputs
$ * $ @: All command line parameters
$? : Exit status of the previous command
$ ID of the executing Process
3) Environment Variables
4) predefined Variables
3. Shell programs and statements
A shell program consists of zero and multiple shell statements. The shell statements include:
Descriptive statement: starts with # and ends with the end of the row;
Functional statements: shell commands, user programs, and other Shell programs;
Structured statements: conditional test, multi-path branch, cyclic statement, and cyclic control statement;
1) descriptive statement
Add # At the beginning of the shell program #! /Bin/sh indicates to tell the OS to use shell of that type to explain how to execute the program.
2) functional statements
Read reads a row from the standard input and assigns values to the following variables. Blocking is possible.

Mathematical operations:

The expr Arithmetic Operation Command is mainly used for simple integer operations, including addition +, subtraction-, multiplication \ *, Division/, and modulo %;

Note:
A) expressions after expr must be separated by spaces.
B) expr supports the following operators: |, &, <, <=, =, and ,! =,> =,>, +,-, *,/, %
C) when using the operators supported by Expr, the following escape characters must be used: |, &, <, <=, >=,> ,*
E) expr only supports integer calculation

Note that there must be spaces between variables and operators, such as: $ expr 1 + 9, and the output result is 10.

In addition, pay special attention to some strange results in the expr command, such as expr 5*2, which may cause errors. In this case, we need to use shell escape characters \ to identify the characters that are easily explained by Shell errors.

Any character:

 

$  expr  5 \* 2$ 10

Note that bash shell contains the expr command to maintain compatibility with the Bourne shell. He must use $ and [] to assign a mathematical operation result to a variable,

For example, $ [operation] circles mathematical expressions:

Note:
A) $ [] use the expression in brackets as a mathematical operation to calculate the result and then output it.
B) before accessing the variables in $ [], add $
C) $ [] only supports integer operations
,

$  v1=$[1 + 5]$ echo $v1$ 6$ v2=$[$v1  *  2]$ 12

The floating point calculation method is as follows:

BC is a simple calculator in Linux. It supports floating point calculation. Input BC in the command line to enter the calculator program. When we want to perform floating point calculation directly in the program, use a simple pipeline to solve the problem.
Note:
1) I tested that BC supports all operators except bitwise operators.
2) scale should be used in BC for precision setting
3) floating point computing instance

The basic format is variable = 'echo "options; ecpression" | bc'. Check that backquotes are used.

var=3.14 var=`echo "scale=2;$var*3"|bc` echo $var 


The output result is 9.42.

In addition, you can use awk for floating point calculation:

var=1 var=`echo "$var 1"|awk '{printf("%g",$1*$2)}'` echo $var 

The output result is 2.
Introduction:
Awk is a text processing tool and a programming language. As a programming language, awk supports multiple computations, and we can use awk for floating point computing, like the above BC, through a simple pipeline, we can directly call awk in the program for floating point calculation.
Note:
1) awk supports all operators except micro-operation Operators
2) awk has built-in functions such as log, sqr, cos, and sin.

3) floating point computing instance

var=3.14 var=`echo "$var 2"|awk '{printf("%g",sin($1/$2))}'` echo $var 

The output result is 1.


Test can be used to test the attributes of a string integer file.
Tput is used to set the interrupt working mode;
3) Structured statements:

Usage of conditional statements and multi-branch statements:

1. Use the if_then statement
If command
Then
Commands
Fi
Run the command after if first. If the exit status of the command is 0 (the command is successfully executed), all the commands after then and before FI will be executed. Otherwise, it will jump to the back of the FI and continue execution.
2. If-then-else statement
If command
Then
Commands
Else
Commands
Fi
3. nested if statement
If command1
Then
Commands
Elif command2
Then
Commands
Elif command3
Then
Commands
Fi
4. Test command (square brackets [] are synonyms)
Used to provide conditions for judgment
If test condition can also be used without test condition, while [conditon] ([,] must have spaces before and after)
Then
Commands
Fi
There are three condition types:
(1) numerical comparison:-EQ,-ne,-Ge,-GT,-Le, lt
Note: The test command cannot process the floating point values stored in the variable.
When using the bash calculator BC, it only spoofs shell to store floating point values as string values in a variable. This method is good if you only use the echo statement to display the result first. But it does not work in Numeric-oriented functions (such as numerical test conditions. The bottom line is that you cannot use non-integer variables in test.
(2) string comparison: = ,! =, <,>,-N (check whether the string length is greater than 0),-z (check whether the string length is equal to 0)
Equal strings: All punctuation marks and uppercase letters are taken into account for test comparison.
String order: Pay attention to two points:
1) '>', '<' must be escaped with '\'. Otherwise, shell uses them as redirection symbols and regards string values as file names.
2) The order of greater than or less than is different from that of the sort command.
In test, the same letter is in upper case and lower case. In sort, the opposite is true.
String size: when evaluating whether a variable contains data, it is easier to use-N and-Z to detect null variables and uninitialized variables with a length of 0.
(3) file comparison
File comparison is the most powerful and commonly used comparison in shell scripts. Test can test the File status and path. (Frequently used !)
-D file: Check whether the file exists and is a directory
-E file: Check whether the file exists.
-F file: Check whether the file exists and is a file.
-R file: Check whether the file exists and is readable.
-S file: Check whether the file exists and is not empty.
-W file: Check whether the file exists and can be written.
-X file: checks whether the file exists and is executable.
-O file: Check whether the file exists and is owned by the current user.
-G file: Check whether the file exists and whether the default group is the current user group.
File1-nt file2: Check if file1 is newer than file2
File1-ot file2: Check if file1 is older than file2

5. Compound condition Query
[Condition1] & [condition2]
[Condition1] | [condition2]
6. advanced features of if-then
(1) use parentheses to represent Mathematical Expressions
(Expression ))
Expression includes the following operators except standard mathematical operators:
++ ,--,!, ~, **, <, >>,&, |, & |
(2) Use brackets to indicate advanced string processing functions
[[Expression]
Provides the pattern matching function except for the flag string comparison in the test command.
In pattern matching, you can define regular expressions that match string values.

Here is an example of an if nested statement to judge the runyear:

#! /Bin/bash # This script will test if we're in a leap year or not. year = 'date + % y' # The command result can be directly assigned to a variable. To check the return status of a command, use $? If [$ [$ year % 400]-EQ 0]; then Echo "this is a leap year. february has 29 days. "Elif [$ [$ year % 4]-EQ 0]; then if [$ [$ year % 100]-Ne 0]; then # nesting from here echo "this is a leap year, February has 29 days. "Else echo" This is not a leap year. february has 28 days. "fielse echo" This is not a leap year. february has 28 days. "fi

7. Case command
You can use the case command instead of writing all Elif statements to continue to check the same variable value.
The case command is list-oriented to check multiple values of a single variable:
Case variable in
Pattern1 | pattern2) commands1 ;;
Pattern3) commands2 ;;
*) Default commands ;;
Esac
4) Advanced structured statements: For, while, until usage)

1. For Loop usage (for/do/done)

A,... In statement

For variable in seq string
Do
Action
Done
Note: As long as the seq string is separated by space characters, each time... When reading in, the read value is given to the preceding variable in order.

#!/bin/bashfor i in $(seq 10)do    echo $idone

B. For (assign value; condition; Operation statement ))
For (assign value; condition; Operation statement ))
Do
Action
Done;

#!/bin/bashfor((i=1;i<=10;i++))do    echo $idone

2. Use while loop (while/do/done)

While Condition Statement
Do
Action
Done

#!/bin/bashi=12while [[ $i -gt 6 ]]do    echo $i    ((i--))done

3. Until statement

Until Condition
Do
Action
Done
It means to exit after the condition is met. Otherwise, execute action.

#!/bin/bashi=5until [[ $i -lt 0 ]]do   echo $i   ((i—))done

Echo-N indicates the linefeed after the statement is omitted. By default, there is a linefeed. In the following code, \ c indicates no line feed after the printed statement; \ B Indicates backspace \ f indicates clear screen;



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.