Detailed introduction to basic learning of Linuxshell scripts (2

Source: Internet
Author: User
Next, let's take a look at how to use Heredocuments and functions in shell.

Next, we will introduce the basic learning of Linux shell scripts in detail. (1) Let's take a look at the use of Here statements and functions in shell.

6. Here documents

HERE Document is one of the ways to define block variables in bash.

The format is as follows:

Command <

...

...

...

HERE

It can be used to define a variable, and the content between the command and HERE is transferred to the input method for processing. HERE is equivalent to a tag, which can be any string. Note that there should be no spaces at the end of the next HERE. Otherwise, an error will be reported.

Use HERE Document to set variables:

View sourceprint?
1 [aa @ aa shell] $ wow = 'wow, great! '

2 [aa @ aa shell] $ m1 = $ (cat <

3> Line 1 is good.

4> They are jack, marry and john.

5> $ wow

6> Here

7>)

8 [aa @ aa shell] $ echo $ m1

9 Line 1 is good. They are jack, marry and john. Wow, great!
Note that HERE is a special usage:
If you add-or ''to the HERE field, adding-indicates that all the TAB keys in the text section below will be ignored. Adding'' indicates that ''is used for the following variable definitions '', this will make the variables show what you see is what you get, that is, disable variable Replacement. if you add "" double quotation marks, the variables will be replaced.

View sourceprint?
1 [aa @ aa shell] $ wow = 'wow, great! '

2 [aa @ aa shell] $ m1 = $ (cat <'where'

3> Line 1 is good.

4> They are jack, marry and john.

5> $ wow

6> Here

7>)

8 [aa @ aa shell] $ echo $ m1

9 Line 1 is good. They are jack, marry and john. $ wow
Note: $ wow is output as is. As for the effect of "add-", we will not elaborate here. you can test it on your own.

It can also be used to define a comment and use the HERE Document to annotate multiple rows:

: < This is the first line of annotation
This is the second line of annotation
This is the third line of annotation
Other rows, and so on
HERE


: Indicates that nothing is done.
Originally, bash only supports single-line comments (represented by #). now it can be used for multi-line comments.

When you want to pass several lines of text to a command, here statements is a good method. It is very useful to write a helpful text for each script. if we have the here documents, we do not need to use the echo function to output a row. A "Here document" starts with <, followed by a string, which must also appear at the end of the here document.

Here is an example. In this example, we rename multiple files and print the help using here documents:

View sourceprint?
01 #! /Bin/sh

02 # we have less than 3 arguments. Print the help text:

03 if [$ #-lt 3]; then

04 cat <

05 -- renames a number of files using sed regular expressions

06 USAGE: $0 'regexp ''' replacement 'files...

07 EXAMPLE: rename all *. HTM files in *. html:

08 $0 'htm $ 'html' *. HTM

09 help

10 exit 0

11 fi

12

13 OLD = "$1"

14 NEW = "$2"

15 # The shift command removes one argument from the list

16 # command line arguments.

17 shift

18 shift

19 # $ * contains now all the files:

20 for file in $ *; do

21 if [-f "$ file"]; then

22 newfile = 'echo "$ file" | sed "s/$ {OLD}/$ {NEW}/g "'

23 if [-f "$ newfile"]; then

24 echo "ERROR: $ newfile exists already"

25 else

26 echo "renaming $ file to $ newfile ..."

27 mv "$ file" "$ newfile"

28 fi

29 fi

30 done
Run the script:

View sourceprint?
1 [aa @ aa shell] $ ll

2 total usage 4

3-rw-r --. 1 yongli 0 February 17 14:06 a.html

4-rw-r --. 1 yongli 0 February 17 14:06 B .html

5-rw-r --. 1 yongli 0 February 17 14:06 c.html

6-rwxrwxr-x. 1 yongli 681 February 17 14:21 here_doc.sh
View sourceprint?
1 [aa @ aa shell] $/data/shell/here_doc.sh

2

3 -- renames a number of files using sed regular expressions

4 USAGE:/data/shell/here_doc.sh 'regexp ''' replacement 'files...

5 EXAMPLE: rename all *. HTM files in *. html:

6/data/shell/here_doc.sh 'htm $ 'html' *. HTM
View sourceprint?
1 [aa @ aa shell] $/data/shell/here_doc.sh 'htm $ 'html' *. htm

2

3 renaming a.htm to a.html...

4 renaming B .htm to B .html...

5 renaming c.htm to c.html...
The following describes in detail.

The first if expression determines whether the number of input command line parameters is smaller than 3 (special variable $ # indicates the number of parameters included ). If the number of input parameters is less than three, the help text is passed to the cat command and then printed on the screen by the cat command. Print the help text and exit the program ($0: indicates the name of the current script ).

If the input parameter is equal to or greater than three, we assign the first parameter to the variable OLD, and the second parameter to the variable NEW.

Next, we use the shift command to delete the first and second parameters from the parameter list, so that the original third parameter becomes the first parameter in the parameter list $.

Then we start the loop. the command line parameter list is assigned to the variable $ file one by one.

Then we determine whether the file exists. If yes, we use the sed command to search for and replace the file to generate a new file name. Then, assign the command result in the backslash to newfile. In this way, we can achieve our goal: get the old and new file names. Use the mv command to rename the file.

HERE we will look at another example and use HERE Document to package the original code of C (or other programming languages. This is the most popular way for Cracker to spread security vulnerability programs.

View sourceprint?
01 #! /Bin/bash

02 # Filename: create_prg.sh

03 echo "creating hello. c ..."

04 echo

05 cat <'eof '> hello. c

06 # include

07 int main ()

08 {

09 printf ("Hello world! \ N ");

10 return 0;

11}

12 EOF

13 echo "compiling hello. c ..."

14 # compile hello. c, create the excutable file

15 gcc-o hello. c

16

17 # if compile successfully, then excute it

18 if [$? -Eq 0]; then

19 echo "excute hello ..."

20 chmod u + x hello

21./hello

22 else

23 echo 'compile Error: hello. c'

24 fi
7. Functions

A function is a collection of commands. a function can break down a large command set into several small tasks. Programmers can further construct more complex Shell programs based on functions without having to write the same code repeatedly.

Basic form:

Function_name ()
{
Command1
Command2
...
CommandN
}

Explain the function structure:
The title: function name, function body: the command set in the function. when writing a script, note that the title name should be unique. if it is not unique, an error will occur during script execution.
You can add the keyword function before the function name, but adding or omitting the keyword function does not affect the final execution of the script.
The command set in the function body must contain at least one command, that is, the function does not allow empty commands, which is different from the C language.
Functions can interact with each other through Parameters and function return values. The order in which a function appears in the script can be arbitrary, but these functions must be executed in the order of calls in the script.
Passing parameters to functions
In bash Shell programming, parameters passed to functions are still transmitted in the form of location parameters, rather than other Form variables such as arrays, this is different from function passing in C or Java.

Function1.sh

View sourceprint?
01 #! /Bin/bash

02

03 half ()

04 {

05 let "n = $1"

06 let "n = n/2"

07 echo "In function half () n is $ n"

08}

09 if [-z $1]; then

10 echo 'Please input number m .'

11 echo "Uage: $0 number"

12 echo "Example: $0 2"

13 exit 0

14 fi

15 let "m = $1"

16 echo "Before the function half () is called, m is $ m"

17 half $ m

18 echo "After the function half () is called, m is $ m"
In Linux Shell programming, functions can also pass indirect parameters. However, this method is far from flexible in C and Java languages. Instead, you can only use indirect variable references to pass parameters, this method is a clumsy indirect parameter transfer method.

Function2.sh

View sourceprint?
01 #! /Bin/bash

02

03 ind_func ()

04 {

05 echo "$1"

06}

07

08 if [-z $1]; then

09 echo 'Please input arguments .'

10 echo "Uage: $0 args"

11 echo "Example: $0"

12 exit 0

13 fi

14

15 parameter = ind_arg

16 ind_arg = Hello

17

18 ind_func "$ parameter"

19

20 ind_func "$ {! Parameter }"

21

22 echo "***********************"

23

24 ind_arg = World

25 ind_func "$ parameter"

26 ind_func "$ {! Parameter }"
Function return value
Sometimes it is necessary to return a specific value after the script is executed to complete subsequent operations of the script. these specific values are the return values of the function. In Linux Shell programming, the function returns its exit status through return. 0 indicates no error, and 1 indicates an error. The return statement can be selected in the script, because the function will execute the subsequent operation where the function is called after the last statement is executed.

Function3.sh

View sourceprint?
01 #! /Bin/bash

02

03 show_week ()

04 {

05 echo-n "What you input is :"

06 echo "$1"

07

08 case $1 in

09)

10 echo "Today is Sunday ."

11 return 0 ;;

12)

13 echo "Today is Monday ."

14 return 0 ;;

15)

16 echo "Today is Tuesday ."

17 return 0 ;;

18)

19 echo "Today is Wednesday ."

20 return 0 ;;

21)

22 echo "Today is Thursday ."

23 return 0 ;;

24)

25 echo "Today is Friday ."

26 return 0 ;;

27)

28 echo "Today is Saturday ."

29 return 0 ;;

30 *)

31 return 1 ;;

32 esac

33}

34

35 if show_week "$1"

36 then

37 echo "What you input is right! "

38 else

39 echo "What you input is wrong! "

40 fi

41 exit 0
Put multiple functions in the script
Multiple functions can be placed in the script. these functions are executed in the order in which the function is called During script execution.

Function4.sh

View sourceprint?
01 #! /Bin/bash

02

03 show_week ()

04 {

05 for day in Monday Tuesday Wednesday Thursday Friday Saturday Sunday

06 do

07 echo-n "$ day"

08 done

09 echo ""

10}

11

12 show_number ()

13 {

14 for (integer = 1; integer <= 7; integer ++ ))

15 do

16 echo-n "$ integer"

17 done

18

19 echo ""

20}

21

22 show_square ()

23 {

24 I = 0

25

26 until [["$ I"-gt 7]

27 do

28 let "square = I * I"

29 echo "$ I * $ I = $ square"

30 let "I ++"

31 done

32}

33

34 show_week

35 show_number

36 show_square
Mutual function call
In Linux Shell programming, functions can be called to each other. when called, the currently running function is stopped and transferred to the called function until the called function is completed, then return to the current function to continue running.
One function calls multiple functions
In Linux Shell programming, a function can call multiple functions. when a function calls other functions, it also needs to execute the called functions in the call sequence.
Local and global variables
In Linux Shell programming, you can declare local variables in Shell functions using the local keyword. local variables are limited to the function scope. In addition, the function can also call global variables outside the function. if a local variable and a global variable name are the same, the local variable will overwrite the global variable in the function.
Function recursion
In Linux Shell, you can call a function recursively, that is, a function can call itself directly or indirectly. In recursive calls, the main function is also called. Executing a recursive function will call itself repeatedly, and each call will enter a new layer.

Function5.sh

View sourceprint?
01 #! /Bin/bash

02

03 # recursively call a function

04 foo ()

05 {

06 read y

07 foo $ y

08 echo "$ y"

09}

10

11 # call a function

12 foo

13 exit 0
Recursion using local variables is generally used for numerical operation. The factorial operation is a recursive call process that uses local variables and implements n! Can be expressed by the following formula:
N! = 1 (n = 0)
N! = N * (n-1 )! (N> = 1)
The factorial operation can be implemented according to this formula, because the factorial operation contains the termination condition "0! = 1 ", so you can use function recursion to implement this operation.

Function6.sh

View sourceprint?
01 #! /Bin/bash

02 # factorial of $1

03

04 fact ()

05 {

06 local num = $1

07 if ["$ num"-eq 0]

08 then

09 factorial = 1

10 else

11 let "decnum = num-1"

12 fact $ decnum

13 let "factorial = $ num * $? "

14 fi

15 return $ factorial

16}

17

18 if [-z $1]; then

19 echo 'Please input an intger number argument .'

20 echo "Uage: [$0 args]"

21 echo "Example: [$0 5]"

22 exit 0

23 fi

24

25 fact $1

26 echo "Factorial of $1 is $? "

27 exit 0
OK. here, I will try it out and write it later.

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.