Shell Script Learning I

Source: Internet
Author: User
Tags arithmetic arithmetic operators array definition array length bit set delete key echo command

Shell Script I

Shell There are two ways to execute a command:

    • Interactive (Interactive): Explains the execution of a user's command, the user enters a command, and the shell interprets the execution of a single rule.
    • Batch: The user writes a shell script in advance, with a number of commands that allow the shell to execute the commands at once without having to strike a single command

The common shell scripting interpreter on Unix/linux has bash, sh, csh, Ksh, and so on, which are customarily called a shell, and bash is the default shell of the Linux standard, and SH is the default shell,bash of the UNIX standard, fully compatible with SH.

When executing such a program, The interpreter (interpreter) needs to read the source code that we wrote and convert it to the target (object), which is then run by the computer.

1.Shell Script writing:

"#!" is a contract tag that tells the system which shell interpreter to use for this script. Open a text editor, create a new file, a filename. SH has an extension of SH (SH stands for shell). The extension does not affect the execution of the script, see the name is good, if you write Shell script in PHP, the extension is good with PHP.

    1. #!/bin/bash
    2. echo "Hello world!" # Note: The echo command is used to output text to a window.

2.Shell footstep running: (CD to script file corresponding directory:)

A. to run as an executable program :

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

$=>./test.sh #执行脚本

Note that you must write./test.sh, not test.sh./test.sh tells the system that it is looking in the current directory.

B. as an interpreter parameter Run :

$=>/bin/sh test.sh

3.Shell variables:

Note that there can be no spaces between the variable name and the equals sign.  Using a defined variable, simply precede the variable name with the dollar sign ($); Defined variables that can be redefined

    1. Variablename= "Value"
    2. Read Person #Read command gets input from stdin and assigns value to custom variable
    3. echo "Hello, $PERSON"
    4. Variablename= "value2"
    5. for Skill in Ada coffe Action Java
    6. Do
    7. echo "I am good at ${skill}script"
    8. Done
    9. unset variable_name
    10. Use the readonly command to define a variable as a read-only variable, and the value of a read-only variable cannot be changed.
    11. Use the unset command to delete a variable.
    12. The variable cannot be used again after it has been deleted; The unset command cannot delete a read-only variable.

4.- e indicates that the escape character is replaced.

    1. a=10
    2. Echo-e "Value of A is $a \ n"

Escape character

Meaning

\\

Back slash

\a

Alarm, Bell

\b

BACKSPACE (delete key)

\f

Page Break (FF), moving the current position to the beginning of the next page

\ n

Line break

\ r

Enter

\ t

Horizontal tab (Tab key)

\v

Vertical tab

You can suppress escaping by using the-e option of the Echo command, which is not escaped by default, or by using the-N option to prevent the insertion of line breaks.

5. Command replacement:

The shell can execute the command first, save the output temporarily, and output it in the appropriate place.

    1. Date= ' Date '
    2. echo "Date is $DATE"

Note that it is an anti-quote, not a single quote, which is below the ESC key.

6. variable substitution :

Variable substitution can change its value depending on the state of the variable (whether it is empty, whether it is defined, etc.)

Form

Description

${var}

The variable's 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, it returns word but does not change the value of var.

7.Shell Operator: Shell arithmetic operators, relational operators, Boolean operators, string operators, and so on

Native bash does not support simple math operations, but can be implemented with other commands, such as awk and expr,expr (expression evaluation) most commonly used.

    1. Val= ' Expr 2 + 2 '
    2. echo "Total value: $val"
    3. Val= ' expr $a \* $b '
    4. echo "A * B: $val"
    5. if [$a! = $b]
    6. Then
    7. echo "A is not equal to B"
    8. Fi

Two note: There is a space between the expression and the operator; The complete expression is to be ' contained; multiplication sign (*) must be added with a backslash (\) before multiplication can be achieved;

List of arithmetic operators

Operator

Description

Example

+

Addition

The ' expr $a + $b ' result is 30.

-

Subtraction

The ' expr $a-$b ' result is 10.

*

Multiplication

The ' expr $a \* $b ' result is 200.

/

Division

The ' expr $b/$a ' result is 2.

%

Take surplus

The ' expr $b% $a ' result is 0.

=

Assign value

A= $b assigns the value of variable B to a.

==

Equal. Compares two numbers, the same returns true.

[$a = = $b] returns FALSE.

!=

Not equal. Compares two numbers, and returns true if they are different.

[$a! = $b] Returns TRUE.

NOTE: Conditional expressions are placed between square brackets, and spaces, such as [$a = = $b], are wrong and must be written as [$a = = $b].

List of relational operators

Operator

Description

Example

-eq

Detects whether two numbers are equal and returns true for equality.

[$a-eq $b] returns TRUE.

-ne

Detects whether two numbers are equal and returns true if they are not equal.

[$a-ne $b] returns TRUE.

-gt

Detects if the number on the left is greater than the right,

If yes, returns TRUE.

[$a-gt $b] returns false.

-lt

Detects if the number on the left is less than the right,

If yes, returns TRUE.

[$a-lt $b] returns TRUE.

-ge

Detects if the number on the left is large equal to the right,

If yes, returns TRUE.

[$a-ge $b] returns false.

-le

Detects if the number on the left is less than or equal to the right,

If yes, returns TRUE.

[$a-le $b] returns TRUE.

    1. if [$a-eq $b]
    2. Then
    3. echo "$a-eq $b: A is equal to B"
    4. Else
    5. echo "$a-eq $b: A is not equal to B"
    6. Fi

List of Boolean operators

Operator

Description

Example

!

Non-arithmetic, the expression is true returns False,

Otherwise, returns True.

[! false] returns TRUE.

-O

Or operation, there is an expression of true to return true.

[$a-lt 20-o $b-GT 100]

Returns True.

-A

With an operation, two expressions are true to return true.

[$a-lt 20-a $b-GT 100]

returns FALSE.

    1. if [$a-lt 100-a $b-gt 15]
    2. Then
    3. echo "$a-lt 100-a $b-gt 15:returns true"
    4. Else
    5. echo "$a-lt 100-a $b-gt 15:returns false"
    6. Fi

List of string operators

Operator

Description

Example

=

Detects whether two strings are equal and returns true for equality.

[$a = $b] returns FALSE.

!=

Detects whether two strings are equal and returns true if they are not equal.

[$a! = $b] Returns TRUE.

-Z

Detects whether the string length is 0 and returns true for 0.

[-Z $a] returns false.

-N

Detects whether the string length is 0 and does not return true for 0.

[-Z $a] returns true.

Str

Detects whether the string is empty and does not return true for null.

[$a] returns TRUE.

File test operators are used to detect various properties of Unix files.

List of file test operators

Operator

Description

Example

-B File

Detects if a file is a block device file,

If yes, returns TRUE.

[-B $file] returns FALSE.

-C file

Detects if the file is a character device file,

If yes, returns TRUE.

[-B $file] returns FALSE.

-D File

Detects if the file is a directory, and returns True if it is.

[-D $file] returns false.

-F File

Detect whether the file is a normal file (non-directory and device files);

If yes, returns TRUE.

[-F $file] returns TRUE.

-G file

Detects if the file has a SGID bit set,

If yes, returns TRUE.

[-G $file] returns false.

-K File

Detects if the file is set with a sticky bit (Sticky bit),

If yes, returns TRUE.

[-K $file] returns false.

-P File

Detects if the file is a named pipe, and returns True if it is.

[-P $file] returns false.

-U file

Detects if the file has a SUID bit set, and returns True if it is.

[-U $file] returns false.

-R File

Detects if the file is readable and returns true if it is.

[-R $file] returns TRUE.

-W File

Detects if the file is writable and returns true if it is.

[-W $file] returns TRUE.

-X File

Detects if the file can be executed and, if so, returns True.

[-X $file] returns TRUE.

-S file

Detects if the file is empty (file size is greater than 0),

Does not return true for null.

[-S $file] returns TRUE.

-E File

Detects if a file (including directory) exists,

If yes, returns TRUE.

[-e $file] returns TRUE.

    1. if [-F $file]
    2. Then
    3. echo "File is an ordinary file"
    4. Else
    5. echo "This is Sepcial file"
    6. Fi

8.Shell string :

Single quote string limit:str= ' This is a 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).

Advantages of double quotes:

    • You can have variables in double quotes.
    • Escape characters can appear in double quotes

Stitching Strings :

    1. Your_name= ' QINJX '
    2. Str= "Hello, I know your is \" $your _name\ "! \ n "
    3. greeting= "Hello," $your _name "!"
    4. greeting_1= "Hello, ${your_name}!"

Get string Length:

    1. string= "ABCD"
    2. echo ${#string} #输出 4
    3. Expr Length "$string"

Extract substring :

    1. String= "Alibaba is a great company"
    2. Echo ${string:1:4} #输出liba

Finding substrings :

    1. String= "Alibaba is a great company"
    2. echo ' expr index ' $string ' is '

9.Shell array: Shell array definition, array length

in the Shell , the array is represented by parentheses, and the array elements are " Space " symbol split open. The general form of the definition array is:array_name= (value1 ... valuen)

    1. Array_name= (value0 value1 value2 value3)
    2. # You can also define individual components of an array individually:
    3. Array_name[0]=value0
    4. Array_name[1]=value1

The general format for reading array element values is: ${array_name[index]}

    1. VALUEN=${ARRAY_NAME[2]}

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

    1. Echo ${array_name[*]
    2. Echo ${array_name[@]}

The method of getting the length of the array is the same as getting the string length, for example:

    1. # Gets the number of array elements
    2. length=${#array_name [@]} #或者:
    3. length=${#array_name [*]}
    4. # Gets the length of an array of individual elements: this is the length of the first element.
    5. lengthn=${#array_name [n]}


Shell Script Learning I

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.