Preliminary understanding of shell scripts

Source: Internet
Author: User
Tags php programming

I. Brief INTRODUCTION 1. What is a shell

The shell is a program written in C that is a bridge for users to use Linux.

The shell is a command language and a programming language.

The shell can also refer to an application that provides an interface that allows the user to access the operating system's kernel through the interface (e.g. Ken Thompson's sh is the first Unix Shell, and the graphical interface of Windows Explorer)

2.Shell Script

Shell script, a scripting program written for the shell.

The shell is generally referred to as shell scripts, but in fact we need to know that shell and shell script is two different concepts.

For reasons of habit and brevity, the "shell programming" appearing in this article refers to Shell scripting, not the development of the shell itself.

3.Shell Environment

Shell programming is like Java and PHP programming, as long as there is a text editor that can write code and a script interpreter that can explain execution.

There are many types of shell in Linux, as follows:

    • 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)
    • ......

Its bash (Bourne Again Shell) is widely used for free and easy to use. Bash is also the default shell for most Linux systems.

In general, it is not differentiated between the Bourne shell and the Bourne Again shell so, like #!/bin/sh, it can also be changed to #!/bin/bash.

Note: #! Tells the system that the program specified after the path is the shell that interprets this script file.

ii. Writing shell scripts1. First shell script

Punch-In Text editor (you can use the Vi/vim command to create a file), a new file test.sh (SH for the shell), the extension does not affect the script execution, knock down the following code:

#!/bin/bashecho "Hello World!"

#! is a contract tag that tells the system what interpreter the script needs to execute, even if it uses a Shell

2.Shell Script RunThere are two ways to run a shell script:1) as an executable program

Save the above code as test.sh and CD to the appropriate directory:

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

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 no test.sh, and only/bin,/sbin, /usr/bin,/usr/sbin wait 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.

2) as an interpreter parameter

This works by running the interpreter directly, whose parameters are the file names of the shell scripts, such as:

/bin/sh test.sh
3.Shell Variables

When you define a variable, the variable name does not add a $ symbol, such as:

My_name= "Liual"

Note that there can be no spaces between the variable name and the equals sign, and that the name of the variable names need to follow the following rules:

    • The first character must be a letter (a-z,a-z)
    • There can't be spaces in the middle
    • Punctuation cannot be used
    • You can't use the keywords in bash (you can keep keywords with help queries)

In addition to explicit direct assignment, you can assign a value to a variable using a statement, such as:

For file in ' ls/etc '

The above statement loops the file name of the directory under/ect

3) Using variables

Add a $ symbol before the variable, such as:

Your_name= "Jack" Echo $your _nameecho ${your_name}

The second outer curly brace is optional and does not add, but if the other character must be added to the identity boundary, such as

For skill in Ada coffe Action Java; Do    Echo ' I am good at ${skill}script ' done

If you do not add curly braces to the skill variable and write the echo "I am good at $skillScript", the interpreter will treat $skillscript as a variable (whose value is null) and the result of the code execution is not what we expect it to look like.

It is a good programming habit to add curly braces to all variables.

A defined variable can be redefined, such as:

Your_name= "Tom" Echo $your _nameyour_name= "Alibaba" Echo $your _name

This is legal, but note that the second assignment can not be written $your_name= "Alibaba", the use of variables when the dollar symbol ($).

4) Read-only variable

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

The following example attempts to change a read-only variable, resulting in an error:

#!/bin/bashmyurl= "http://www.w3cschool.cc" readonly myurlmyurl= "http://www.runoob.com"

Run the script with the following results:

/bin/sh:name:this variable is read only.
5) Delete 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.

Instance

#!/bin/shmyurl= "http://www.baidu.com" unset myurlecho $myUrl

The above instance execution will have no output.

Variable type

When you run the shell, there are three different variables:

    • 1) local variable local variables are defined in a script or command, only valid in the current shell instance, and other shell-initiated programs cannot access local variables.
    • 2) Environment variables All programs, including shell-initiated programs, can access environment variables, and some programs require environment variables to keep them running properly. Shell scripts can also define environment variables when necessary.
    • 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 which are local variables that guarantee the shell's normal operation.
3.Shell string

Strings are the most common and useful data types in shell programming (except numbers and strings, and no other type works well), strings can be in single quotes or double quotes, or without quotes. The difference between single and double quotes is similar to PHP.

1) Single quotation mark
Str= ' This is a string '

Single-Quote String restrictions:

    • 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) Double quotes
Your_name= ' Jack ' str= "Hello, I know your is \" $your _name\ "! \ n "

Advantages of double quotes:

    • You can have variables in double quotes.
    • Escape characters can appear in double quotes
3) Stitching strings
Your_name= "Jack" greeting= "Hello," $your _name "!" greeting_1= "Hello, ${your_name}!" echo $greeting $greeting _1
Get string length
string= "ABCD" Echo ${#string} #输出 4
Extract substring

The following instance intercepts 4 characters from the first 2 characters of the string:

String= "You is a good man" Echo ${string:4:6} # output is
Finding substrings

Find the location of the character "I or s":

string= "I am Good Man" echo ' expr index ' $string ' AM '  # output 2

Note: the "'" in the above script is an anti-quote, not a single quote "'", don't look wrong.

Shell Array

Bash supports one-dimensional arrays (which do not support multidimensional arrays) and does not limit the size of arrays.

Similar to the C language, the subscript of an array element is numbered starting with 0. Gets the elements in the array to take advantage of subscript, the subscript can be an integer or an arithmetic expression whose value should be greater than or equal to 0.

Defining arrays

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 = (value 1 value 2...) value n)      

For example:

Array_name= (value0 value1 value2 value3)

Or

Array_name= (VALUE0VALUE1VALUE2VALUE3)

You can also define individual components of an array individually:

Array_name[0]=value0array_name[1]=value1array_name[n]=valuen

You can not use successive subscripts, and there is no limit to the range of subscripts.

Reading an array

The general format for reading array element values is:

${array name [subscript]}

For example:

Valuen=${array_name[n]}

Use the @ symbol to get all the elements in the array, for example:

Echo ${array_name[@]}
Gets 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 [@]}# or length=${#array_name [*]}# Gets the length of the single element of the array lengthn=${#array_name [n]}
Shell annotations

Lines that begin with "#" are comments, which are ignored by the interpreter.

There is no multiline comment in sh, only one # is added to each line. Can only be like this:

#--------------------------------------------# This is a note # author:liual# message: It's a fine day! #--------------------------------------------##### user Config area start ######## Here you can add script description information # ###### User Configuration area end  #####

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.

 

Preliminary understanding of shell scripts

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.