Shell Programming Notes

Source: Internet
Author: User
Tags arithmetic operators bit set case statement delete key echo command stdin

####### #认识shell
The common shell scripting interpreters on 1.unix/linux include bash, sh, csh, Ksh, and so on, which are used to call them a shell. We often say that there are many kinds of shells, actually speaking of shell script interpreter.
Note: BASH is the acronym for the Bourne Again shell, the default shell for the Linux standard, which is based on the Bourne shell and absorbs some of the features of the C shell and Korn shell. Bash is fully compatible with SH, meaning that scripts written in SH can be executed without modification in bash.

2.#!/bin/bash
"#!" 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.

3.chmod +x./test.sh Script Add Execute permissions
Note, be sure to write./test.sh, not test.sh. Run other binary programs also, the direct write Test.sh,linux system will go to the path to find there is not called test.sh, and only/bin,/sbin,/usr/bin,/usr/sbin, etc. in path, your current directory is usually not in path, So write test.sh will not find the command, to use./test.sh tells the system that it is looking in the current directory.

The 4.read command obtains input from stdin and assigns it to the person variable, and finally outputs on stdout:
#!/bin/bash

#Author: HJY
#Script follows Here:[email Protected]:/root

echo "What ' s your name?"
Read person
echo "Hello, $Person"

####### #shell变量
1.mynum=8
Note that there can be no spaces between the variable name and the equals sign

2. Using a defined variable, simply precede the variable name with the dollar sign ($)
My_name= "Hjy"
Echo $my _name
Echo ${my_name}
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

3. Defined variables that can be redefined
Myurl= "http://see.xidian.edu.cn/cpp/linux/"
Echo ${myurl}
Myurl= "http://see.xidian.edu.cn/cpp/shell/"
Echo ${myurl}

4. Use the readonly command to define a variable as a read-only variable, and the value of a read-only variable cannot be changed.

5. 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

####### #shell特殊变量
1. Variables that contain other characters have special meanings, called special variables.
$ A: The file name of the current script
$n: Arguments passed to a script or function. N is a number that represents the first few parameters. For example, the first parameter is $ $, and the second argument is $ A.
$#: The number of arguments passed to a script or function.
$*: All parameters passed to the script or function.
[Email protected]: All parameters passed to the script or function. When enclosed by double quotation marks (""), it is slightly different from $*, the difference is as follows 2:
$?: The exit state of the last command, or the return value of the function.
$$: The current shell process ID. For shell scripts, this is the process ID where the scripts are located.
Sample script:
#!/bin/bash
echo "File Name: $"
echo "First Parameter: $ $"
echo "Second Parameter: $"
echo "Quoted Values: [Email protected]"
echo "Quoted Values: $*"
echo "Total number of Parameters: $#"
Execute script $./test.sh Tom Bob
File Name:./test.sh
First Parameter:tom
Second Parameter:bob
Quoted Values:tom Bob
Quoted Values:tom Bob
Total number of Parameters:2
The difference between 2.$* and [email protected]:
$* and [email protected] All represent all parameters passed to a function or script, and are not enclosed by double quotation marks (""), with "$" and "$" ... All parameters are output in the form "$n".
But when they are enclosed in double quotation marks (""), "$*" takes all parameters as a whole and outputs all parameters in the form of "$ $ ... $n"; "[email protected]" will separate the parameters to "$" "$" ... All parameters are output in the form "$n".
eg:for var in "$*" "minus double quotes, after execution the output is whole"
Do
echo "$var"
Done
Execution: Sh test.sh a b C

3.$? You can also represent the return value of a function

4.ECHO-E where-e indicates an escape character substitution, which is output if the-e option is not used
ECHO-E where-E is not escaped and is not escaped by default; Use the-n option to disallow insertion of line breaks
Escape character: Meaning
\ \: Back slash
\a: Alarm, Bell
\b: Backspace (delete key)
\f: Page Break (FF), moves the current position to the beginning of the next page
\ n: Line break
\ r: Enter
\ t: Horizontal tab (Tab key)
\v: Vertical tab

5. Syntax for command substitution:
' Command '
Note that it is an anti-quote, not a single quotation mark, which is below the ESC key.

6. Variable substitution forms that can be used
Form: Description
${var}: Variable original value
${var:-word}: If the variable var is empty or has been deleted (unset), then return to word, but do not change the value of var.
${var:=word}: If the variable var is empty or has been deleted (unset), return to Word and set the value of Var to word.
${var:?message}: If the variable var is empty or has been deleted (unset), then send message messages to the standard error output, which can be used to detect whether Var can be properly assigned. If this substitution appears in the shell script, the script will stop running.
${var:+word}: If the variable var is defined, then return to word, but do not change the value of var.

####### #shell运算符
1. Arithmetic operators
Operator Description Example
+ addition ' expr $a + $b ' result is 30. (a=10 b=20)
-Subtraction ' expr $a-$b ' result is 10.
* multiply ' expr $a \* $b ' result is 200.
/Division ' expr $b/$a ' result is 2.
% "Expr $b% $a ' result is 0.
= Assignment A= $b assigns the value of variable B to a.
= = Equal.  Used to compare two numbers, the same returns true. [$a = = $b]
! = is not equal.  Compares two numbers, and returns true if they are different. [$a! = $b]

Native bash does not support simple math operations, but can be implemented with other commands, such as awk and expr,expr, which are most commonly used.
Expr is an expression evaluation tool that uses it to perform evaluation operations on expressions.
Script Example:
Val= ' Expr 2 + 2 '
echo "Total value: $val"
Execution Result: Total Value:4
Attention:
Equal sign with Val no spaces
There are spaces between the expression and the operator, such as the 2 + 2, which is different from most of the programming languages we are familiar with.
The complete expression is to be included, note that this character is not a common single quote, and this key is below the ESC key.

2. List of relational operators
Operator Description Example
-EQ detects whether two numbers are equal and returns true for equality. [$a-eq $b]
-ne detects whether two numbers are equal and returns true if they are not equal. [$a-ne $b]
-GT detects if the number on the left is greater than the right and, if so, returns True. [$a-gt $b]
-LT detects if the number on the left is less than the right and, if so, returns True. [$a-lt $b]
-ge detects if the number on the left is large equal to the right, and returns true if it is. [$a-ge $b]
-le detects if the left-hand number is less than or equal to the right, and returns true if it is. [$a-le $b]

Note: Relational operators only support numbers, and strings are not supported unless the value of the string is a number.

3. List of Boolean operators
   operators                           &NBSP ;   Description                                                            Example

!     Non-operation, the expression is true returns False, otherwise true. [! false]
-O or operation, which returns true if an expression is true. [$a-lt 20-o $b-GT 100]
-A with operation, two expressions are true to return true. [$a-lt 20-a $b-GT 100]

4. Character-wearing Operation list
Operator Description Example

= detects whether two strings are equal and returns true for equality. [$a = $b]
! = detects whether two strings are equal, and returns true if they are not equal. [$a! = $b]
-Z detects if the string length is 0 and returns true for 0. [-Z $a]
-N detects whether the string length is 0 and does not return true for 0. [-N $a]
STR detects if the string is empty and does not return true for null. [$a]

5. List of file test operators

Example of operator description
The-B file detects whether the files are block device files and, if so, returns True. [-B $file]
The-C file detects whether the files are character device files and, if so, returns True. [-B $file]
The-D file detects whether the files are directories and, if so, returns True. [-D $file]
The-F file detects if the files are normal files and returns true if they are. [-F $file]
The-G file detects if the SGID bit is set and returns True if it is. [-G $file]
The-K file detects whether the files have a sticky bit set (Sticky bit), and returns True if it is. [-K $file]
The-P file detects whether the files are named pipes and, if so, returns True. [-P $file]
-U file detects whether the file has a SUID bit set and returns True if it is. [-U $file]
The-R file detects whether the files are readable and, if so, returns True. [-R $file]
The-W file detects whether the files are writable and, if so, returns True. [-W $file]
The-X file detects whether files can be executed and, if so, returns True. [-X $file]
-S file to detect whether the files are empty (the file size is greater than 0) and not NULL to return TRUE. [-S $file]
The-e file detects whether files (including directories) exist and, if so, returns True. [-E $file]

####### #shell注释
What if, in the course of development, you encounter a large segment of code that needs to be annotated temporarily and then uncomment later? Each line with a # symbol is too laborious, you can put this piece of code to be annotated with 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.


####### #Shell字符串
1. Limitations of single-quote strings:
Any character in a single quotation mark is output as is, and 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).

2. Advantages of double quotes:
You can have variables in double quotes.
Escape characters can appear in double quotes

###### #Shell数组
1. In the shell, the array is represented by parentheses, and the elements of the array are separated by a "space" symbol. The general form of the definition array is:
Array_name= (value1 ... valuen)

2. Reading an array
1) The general format for reading array element values is:
${array_name[index]}

Use @ or * to get all the elements in the array, for example:
${array_name[*]}
${array_name[@]}

2) Get the length of the array
The method of getting the length of the array is the same as getting the string length, for example:
# Gets the number of array elements
length=${#array_name [@]}
length=${#array_name [*]}
# Gets the length of an array of individual elements
length=${#array_name [n]}

####### #Shell echo Command
1.echo command to print out the specified string on the screen

If the variable is connected to another character, you need to use curly braces ({}):
Mouth=8
echo "${mouth}-1-2009"

2. Display results redirected to file
echo "It is a test" > myfile

####### #Shell printf Command
The 1.printf command is used to format the output, is an enhanced version of the Echo command, and printf does not wrap like echo, and must explicitly add line breaks (\ n).

Syntax for the 2.printf command:
printf format-string [arguments ...]
Format-string is the format control string and arguments is the parameter list. If there is no arguments, then%s is replaced with NULL,%d replaces with 0
This is only a description of the difference from the C-language printf () function:
printf command without parentheses
Format-string can be without quotation marks, but it is best to add single quotes and double quotes.
When the parameter is more than the format control (%), format-string can be reused and all parameters can be converted.
Arguments use spaces separated by commas.

##### #Shell If statement
There are three kinds of if ... else statements in 1.Shell:
If ... fi statement;
If ... else ... fi statement;
If ... else ... elif. Fi statement.
2.if. Else statements are also often used in conjunction with the Test command, as follows:
if test $[2*3]-eq $[1+5]; Then echo ' The numbers is equal! '; Fi

####### #Shell Case ESAC statement
1.case ... esac similar to switch...case statements in other languages, it is a multi-branch selection structure.
The case statement matches a value or 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
Command2
Command3
;;
Mode 2)
Command1
Command2
Command3
;;
*)
Command1
Command2
Command3
;;
Esac
Attention:
The value must be followed by in, and each pattern must end with a closing parenthesis
;; Symbols are similar to break in other languages, meaning jumping to the end of the entire case statement.

####### #Shell for Loop
The general format for 1.for loops is:

For variable in list
Do
Command1
Command2
...
CommandN
Done
Sample script: Show files in the home directory that begin with. Bash
#!/bin/bash
For FILE in $HOME/.bash*
Do
Echo $FILE
Done
Execution Result:
/root/.bash_history
/root/.bash_logout
/root/.bash_profile
/root/.bashrc

####### #Shell While loop
The 1.while loop is used to continuously execute a series of commands and to read data from the input file; the command is usually a test condition. The format is:
While command
Do
Statement (s) to BES executed if command is true
Done
Example script: The while loop can be used to read keyboard information. Input information is set to variable film, press <Ctrl-D> to end loop.
echo ' type <CTRL-D> to terminate '
Echo-n ' Enter your most liked film: '
While Read FILM
Do
echo "Great film is the $FILM"
Done

The command finishes, control returns to the top of the loop, and starts from the beginning until the test condition is false.

####### #Shell Break and Continue command to jump out of the loop
The 1.break command allows you to jump out of all loops (terminating all loops following the execution).
Break n means to jump out of the nth layer loop
Sample script:
While:
Do
Echo-n "The number is (1-3):"
Read num
Case $num in
1|2|3) echo "Your number is $num"
;;
*) echo "The number is not a between 1 to 3,game over!"
Break
;;
Esac
Done

The 2.continue command is similar to the break command, with only a little difference, and it does not jump out of all loops and just jumps out of the current loop.
Continue can also be followed by a number, indicating that the first layer jumps out of the loop.
Sample script: echo "Game over!" Will never be executed.
While:
Do
Echo-n "The number is (1-3):"
Read num
Case $num in
1|2|3) echo "Your number is $num"
;;
*) echo "The number is not between 1 to 3!"
Continue
echo "Game over!"
;;
Esac
Done


####### #Shell function
The 1.Shell function is defined in the following format:
Function_name () {
List of commands
[Return value]
}
function return value, you can explicitly increment the return statement, if not added, the last command will run the result as the return value.

2. The delete function can also use the unset command, but add the. f option as follows:
$unset. F function_name
####### #Shell Function parameters
1. Arguments can be passed to a function when it is called. Inside the function body, the value of the parameter is obtained in the form of a $n, for example, $ $ for the first argument, and $ = for the second argument ...
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.

####### #Shell input and output redirection
The 1.linux command obtains input from the standard input device (stdin) By default, outputting the result to the standard output device (STDOUT) display.
In general, the standard input device is the keyboard, the standard output device is the terminal, that is, the display.

2. The syntax for the output redirection is:
$ command > file

Use >> append to end of file
echo Test >> file
3. Enter the syntax for redirection:
Command < file

4. REDIRECT Command list
Command description
Command > file redirects the output to file.
Command < file redirects the input to file.
Command >> file redirects the output to file in an append manner.
n > file redirects the file descriptor n files to filename.
n >> files redirect files with file descriptor N as an append to file.
N >& m merges the output file m and N.
N <& m merges the input file m and N.
<< tag will start to tag the contents of tags between tag and end tag as input.

5. Redirect in-depth explanation
In general, each Linux command will open three files when it is run:
Standard input file (stdin): stdin file descriptor for 0,linux program reads data from stdin by default.
Standard output file (stdout): StdOut file descriptor for 1,linux program outputs data to stdout by default.
Standard error file (stderr): stderr file Descriptor 2,linux program writes an error message to the stderr stream
1) If you want stderr to be redirected to file, write this:
$command 2 > file
2) If you want stderr to append to the end of file, write this:
$command 2 >> file
3) If you want to redirect stdout and stderr to file after merging, you can write:
$command > File 2>&1 or $command >> file 2>&1
4) If you want to redirect both stdin and stdout, you can write:
$command < File1 >file2
The command commands redirect stdin to File1, redirecting stdout to File2.

6./dev/null file
If you want to execute a command but do not want the output to be displayed on the screen, you can redirect the output to/dev/null
Note:/dev/null is a special file, the content written to it will be discarded, and if you try to read from the file, then nothing will be read. However, the/dev/null file is very useful and redirects the output of the command to it, which results in a "no output" effect.

####### #Shell file contains
1.Shell can also include external scripts to merge the contents of external scripts into the current script
. FileName or source filename
The effect is the same in both ways, usually using the dot (.), but note the dot (.) number. There is a space in the middle of the file name.

This article from the "12148275" blog, reproduced please contact the author!

Shell Programming Notes

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.