Shell Getting Started Tutorial (7)-Scripting

Source: Internet
Author: User
Tags echo b echo d

Shell Getting Started Tutorial (1)-shell-JUSTKK's Column-Blog channel-csdn.net
http://blog.csdn.net/justkk/article/details/43795131

Shell Getting Started Tutorial (2)-Variables and Parameters-JUSTKK-Blog channel-csdn.net
http://blog.csdn.net/justkk/article/details/44081993

Shell Getting Started Tutorial (3)-command editor-JUSTKK's column-Blog channel-csdn.net
http://blog.csdn.net/justkk/article/details/44617445

Shell Getting Started Tutorial (4)-Job Control-JUSTKK's column-Blog channel-csdn.net
http://blog.csdn.net/justkk/article/details/46801163

Shell Getting Started Tutorial (5)-arithmetic operations-JUSTKK's column-Blog channel-csdn.net
http://blog.csdn.net/justkk/article/details/47025297

Shell Getting Started Tutorial (6)-Environment-JUSTKK-Blog channel-csdn.net
http://blog.csdn.net/justkk/article/details/47025321

Shell Getting Started Tutorial (7)-Scripting-JUSTKK's Column-Blog channel-csdn.net
http://blog.csdn.net/justkk/article/details/47025397

1. Execute script

The shell is also a high-level programming language, and shell programs are often called scripts that interpret execution and do not require compilation.

The execution of the script needs to read R and execute x permissions, and you can add the appropriate permissions through the chmod command, ls-l View permissions.

Ls-l 0.sh

-rwxr-xr-x. 1 root 8 14:59 0.sh

It can be executed directly through the script name, such as 0.sh, which requires read and execute permissions at this time.

You can also use bash execution, such as Bash 0.sh, where only read permissions are required.

Typically, a shell script is executed in a separate environment:

1. The variables in the current shell need to be export before they can be used in the script

2, in addition, the script will not change the current shell environment.

2. Position parameter

A positional parameter is a special set of variables used to track the parameters of a script whose name contains only numbers, such as:

$ $ means the script name itself, the remaining $. Indicate the parameters of the script in turn

You can use the following script to verify:

echo "Script Name: $"

echo "Number of Args passed: $#"

echo "Arguments passed: $*"

echo "Arg 1=$1,arg 2=$2, arg 3=$3"

Save As 0.sh, execute./0.sh a b C

Special variables:

$# represents the number of parameters, $* and $@ represent all parameters.

The difference between $* and $@: $* takes all parameters as a whole and $@ represents the detached individual. The effect is the same without double quotes.

Positional parameters cannot be modified directly using the Var=value, and you can use the Shift command.

The shift command shifts all the arguments to the left, replacing the parameters on the target position with each parameter, with a corresponding decrease in the number of parameters.

By default, you can specify a parameter that represents the number of moves, such as Shift 2

You can use the following script to verify:

echo "Number of Args passed: $#"

echo "Arguments passed: $*"

echo "Arg 1=$1,arg 2=$2, arg 3=$3"

Shift

echo "Number of Args passed: $#"

echo "Arguments passed: $*"

echo "Arg 1=$1,arg 2=$2, arg 3=$3"

Save As 0.sh, execute./0.sh a b C

3, exit

The exit command exits the execution of the script, and subsequent commands are no longer executed.

You can include a parameter that represents the exit state of the entire script, that is, the execution result.

Such as:

echo "Over"

Exit 1

Save As 0.sh, execute./0.sh

Then look at the exit status of the script in the SHELL, echo $?

4, [[...]] command

This command is used to perform conditional judgments, and can examine file properties, strings, patterns, integers, and so on.

format is [[expression]], note that spaces are required before [[behind and]], and spaces are required on both sides of the operator. Example:

[[$a = 3]] && echo "A is 3"

C=hi; [[$c = h*]] && echo "Begin with H"

a=4; [[$a = + ([0-9]]]] && echo "a number"

String operators

-N String True if length

-O option True if option is set

-A-Z string true if length of of string is zero

string1 = string2 true if string1 is equal to string2

String1!= string2 True if string1 is not equal to string2

String = Pattern true if string matches pattern

String!= pattern True if string does not match pattern

String1 < string2 true if string1 less than string2

String1 > string2 true if string1 greater than string2

For specific use see Man test

Note the comparison of integers, using-GT-LT, etc., cannot use greater than or less than, which is used to compare strings of

[[> 2]] && echo "13>2"

[[13-GT 2]] && echo "Greater than 2"

In fact, the comparison of integers can be used ((..)) command, which is more convenient, where the variables do not need to be added $, and no spaces are required, such as:

A=13 ((a>2)) &&echo ">2"

A little note, the equal comparison of two integers, in ((..)) Internal need to use = =, not =. The meaning of a single equal sign is a value assignment.

in [[..]] The interior can be compared using either = = or a single equal sign.

Similar to the C language,! Represents the logical "non". && Express and, | | Express or. () used to change the priority of an expression.

(((3+2) *4==20)) &&echo "20"

Test or [..] can also be used to perform conditional judgments, they are also the shell's built-in commands. Such as:

Test 1-eq 1 && echo "OK"

[1-eq 1] && echo "OK"

Compared to them, the recommended use [[...]]

Summarize:

1, the integer comparison operation uses ((..)), the other comparison operation uses [[...]]

2, the use of double equals = = To determine whether two operands are equal

5, Control command case perform multiple branch detection, such as:

Case is in

A) echo "a";;

b) echo "B";;

* echo "other";;

Esac for command execution loop

For I in 1 2 3

Todo

Echo $i

Done

Alternatively, the loop variable is then taken from all positional arguments in turn

For I

Todo

Echo $i

Done

Or

For ((i=1;i<10;i++))

Todo

Echo $i

Done if, such as:

A=7

if ((a>10)); then

echo "A>10"

Elif ((a>5)); then

echo "A>5"

Else

echo "A<=5"

Fi while, such as:

A=1

while ((A<10))

Todo

Echo $a

((a++))

Done until, such as:

A=1

Until ((a==10))

Todo

Echo $a

((a++))

Done break jump out of circulation, continue continue to cycle

Its parameters specify the level of the loop, which defaults to 1

such as: Break 2 jump out of the 2-tier cycle

Select, used to display a simple menu and wait for the user's choice, such as:

Select I in Choice-a choice-b choice-c

Todo

echo "You picked selection $REPLY: $i"

Done

Look at the output, show the shell's third command-line prompt PS3, and its default is #?, you can modify and view the effect.

By the way, the last command-line prompt PS4, which is the trace debug prompt, the default is +, when you open the Shell's tracking options, each executed command and its arguments are first displayed, and the PS4 value is added at the beginning of the line. • about annotations

# The content after the end of the line is commented and not executed by the shell.

Pay special attention to the #! of the first line of the script is not a comment, which can be followed by an execution program that indicates that the entire script is interpreted by that executing program. Such as:

#!/usr/bin/awk-f

{Print $}

6, input and output command echo output information, support escape characters

\a Bell character

\b Backspace

\c line without ending newline (remaining arguments)

\f FormFeed

\ NewLine

\ r return

\ t tab

\v Vertical Tab

\ Backslash

\0x 8-bit character whose ASCII code is the 1-, 2-, or 3-digit octal number x

Note that using the escape character requires the-e option, such as:

Echo-e "\044"

Echo-e "A\TB\NCD"

EXEC I/O redirection, using the file descriptor 0-9, such as:

EXEC 5>&1 # Copies the file descriptor, at which point 5 is equivalent to 1, and corresponds to the screen

Echo a>&5 # Write descriptor 5, actually output to screen

EXEC 1>ff.out # REDIRECT Descriptor 1, pointing to file Ff.out

Echo B # output to file Ff.out

EXEC 1>&5 # REDIRECT Descriptor 1 again, point to Descriptor 5, corresponding screen

Echo C # output to screen

EXEC 1>&-# closing descriptor 1

Echo D # Error, because the output is off

read reads the input and deposits it in the variable, such as:

Read a # Waiting for keyboard input, input content into variable a

Read a B # wait for keyboard input, split and put into variable a,b, delimiters are usually whitespace, such as spaces, <tab> IFS variables, to specify the input of the separator, such as: ifs=,

Then the input is separated by commas, read a B, and if you enter 1, 2, the variables A and B are respectively 1 and 2. The read command reads content by default from standard input (that is, descriptor 0), which can be read from other descriptors by the-u option, such as:

EXEC 4<ff.out

Read-u4 B reply variable

If the read command does not specify any variables, the read content is placed in the variable reply, such as:

Read Echo $REPLY

read a trap for the command, view the following scenario:

Unset b C

A= "3 4"

echo $A |read b C

Echo $b, $c

I want the variables B and C to be values 3 and 4, respectively, and the actual validation results: Variables B and C have nothing.

The reason for this is that the read command is executed in a child shell, although 3 and 4 are read in the child shell, but the current shell is not affected.

Modify:

Unset b C

A= "3 4"

Read B c <<!

$A

!

Echo $b, $c

8. Other · command, Source command, both equivalent, executing parameter-specified scripts in the current shell, changing the current shell environment

It is often used to read and execute an environment definition file, assuming that the contents of file 0.sh are as follows:

A=3

B=4

Compare two ways of executing:./0.sh and. The./0.sh function, defined as follows, where the keyword function can be omitted:

function AA ()

{

echo AA

}

After a function is defined, it is invoked in a way that is similar to a normal command, and can also be used to check its exit status.

AA ()

{

echo HH

Return 1

}

AA # call can pass parameters to function, inside function need to use positional parameter to access

echo $?

• Functions defined in the current SHELL are not available by default in the child shell and need to be exported: export-f AA By default, variables and callers in a function are shared

Variables defined before the call can be used in functions, variables defined in functions are still visible after the call is finished, and local keywords can be used to define locals inside the function.

A=1

function AA

{

Local A=3

b=2

echo "in function: $A, $B"

}

Aa

Echo $A, $B • View already defined functions

Use Typeset-f-P or Typeset-f-p to display only the function name, which displays the definition of the function at the same time.

Trap command to capture the signal and perform the corresponding action, such as:

Trap ' echo Nono ' 2 # Capture interrupt Signal

Trap "" 2 # Ignore interrupt signal

Trap 2 # Restore default processing for interrupt signals

A special signal of 0 indicates that the script exits. This signal can be captured to perform some cleanup action when the script exits.

Trap ' echo over ' 0

..

• Debug Scripts

A few useful options:

-N Read only script, not actual, check syntax only

-V Displays line of code read in when the script is read

Display each command and its arguments when-X executes

such as: Sh-x 0.sh

You can customize the prompt displayed by the-X option, such as: Export ps4= ' [$LINENO] '

The line number of each command is then displayed

The trap command can also be used to debug scripts, using special signals such as debug, ERR

Trap ' echo error at line $LINENO ' ERR

Trap ' echo Debug line= $LINENO ' Debug

Every

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.