Shell Scripting Learning

Source: Internet
Author: User

First, preface

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.

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

What I learned here is bash, the Bourne Again Shell, which is widely used in daily work due to its ease of use and free. At the same time, Bash is the default Shell for most Linux systems.

Ii. creation and execution of shell scripts 1. Create Shell scripts

Open a text editor (you can use the Vi/vim command to create a file), a new file test.sh, the extension sh (sh for Shell), the extension does not affect the script execution, see the name is good, if you write a shell script in PHP.

Enter the following code:

#!/bin/bashecho "Hello World!"

The first shell script was created successfully!

2. Execute shell Script 1. As an executable program

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

bianbiandemacbook-pro:~ bianbian$ chmod +x./test.sh   #使脚本具有执行权限
bianbiandemacbook-pro:~ bianbian$./test.sh Hello World! #执行脚本

Be sure to write ./test.sh, not test.sh, run other binary programs as well, direct writing test.sh,linux system will go to the PATH to find there is no test.sh, and only/bin,/sbin,/US R/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 operation is to run the interpreter directly, whose parameters are the file name of the shell script, which runs the script, does not need to specify the interpreter information in the first line, it is useless to write.

bianbiandemacbook-pro:~ bianbian$ sh test.sh Hello world!
3. Shell variable 1, define variable

Variable name does not add dollar sign ($) when defining a variable

My_name= "Bianbian"

Shell variable definition, there can be no space between the variable name and the equal sign, the name of the variable names should follow the following rules:

    • Names can only use letters, numbers, and underscores, and the first character cannot begin with a number.
    • 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).

In addition to explicitly assigning values directly, you can also assign a value to a variable using a statement:

For file in ' ls/etc ' for file in $ (ls/etc) #两种方法都可以, the file name of the directory under/etc is recycled.
2. Using variables
echo $my _nameecho ${my_name}

The curly brackets outside the variable name are optional, plus the curly braces are used to help the interpreter identify the bounds of the variable, 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.

Therefore, it is recommended to add curly braces to all variables.

3. Redefine variables

Redefine directly by rule:

My_name= "Bianbian" Echo $my _namemy_name= "Bianfengjie" Echo $my _name
4. 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. Forcing changes to read-only variables will cause an error:./test.sh:line 6:my_name:readonly Variable

My_name= "Bianbian" Echo $my _namereadonly my_namemy_name= "Bianfengjie"
5. Delete variables

Use the unset command to delete a variable that cannot be used again after it has been deleted. The unset command cannot delete a read-only variable.

My_name= "Bianbian" unset my_name
Echo $my _name
6. Variable type

There are three types of variables in the shell:

    • local variable local variables are defined in a script or command and are valid only in the current shell instance, and other shell-initiated programs cannot access local variables.
    • 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.
    • 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.
4. 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.

1. String definitions
My_name= "Bianbian" str1= ' My name is bianbian! ' Str2= "My name is \" $my _name "\! \ n "

Single Quote string:

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

Double quote string:

    • You can have variables in double quotes.
    • Escape characters can appear in double quotes
2. String manipulation
    • Stitching strings
My_name= "Bianbian" str= "Hello," $my _name "!" str_1= "Hello, ${my_name}!" echo $str $str _1
    • Get string length, extract substring, find substring
string= "ABCD" Echo ${#string} #输出 4string= "Bianbian is a Girl" Echo ${string:1:4} # 4 characters starting from the 2nd character of a string, output Ian
' Expr index ' $string ' io '  # Look for the position of the character I or o (which letter appears first, which is calculated), Output 4

Note: The above script is ' inverted quotation marks, not single quotes '   

5. Shell Array

Bash supports one-dimensional arrays, does not support multidimensional arrays, but 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.

1. Defining arrays

In the Shell, the array is represented by parentheses, and the elements of the array are separated by a "space" symbol.

Array name = (value 1 value 2 ...) Value N)
Array_Name= (value0 value1 value2 value3)  
Array_Name= (value0value1value2value3)
Array_Name[0]=value0array_name[1]=value1array_name[n]= Valuen #可以不使用连续的下标, and there is no limit to the range of subscripts. 
2. Reading an array

The general format for reading array element values is:

${array name [subscript]}valuen=${array_name[n]}echo ${array_name[@]} #使用 @ symbol to get all the elements in the array

Example:

#!/bin/basharray= (1 2 3 4) A=${array[2]}echo ${array[@]}echo $a

Execution Result:

bianbiandemacbook-pro:~ bianbian$ chmod 777 test1.sh bianbiandemacbook-pro:~ bianbian$./test1.sh 1 2 3 43
3. Get the length of the array

The method of getting the length of the array is the same as getting the string length

  

 

  

  

  

  

  

 

Shell Scripting Learning

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.