Shell Programming--function Chapter

Source: Internet
Author: User
Tags function definition integer numbers

One: function classification

  1. Local function (local variable)
    local variable name. modifications to variables in the local function are only valid during the current function run.
    Func1 () {local Name=test;echo "func1:name= $name"; local Age=18;echo "func1:age= $age"; Echo $$;}

  2. Global functions (Local variables)
    Without local and declare-i (integer numbers only) The default is global, and Declare-ig is also a global function (local variable). Global function modification and assignment of variables are valid for the current shell. But the child shell does not inherit
    Func1 () {name=test; declare-i age=16; echo "Func1:name= $name, func1:age= $age";}

  3. Environment function (environment variable)
    Variables in the DECLARE-XF environment function inherit or export-f from the child shell


    Exercise 1: Use a function to write a script to print a chess board, requiring each grid to consist of 8 spaces.
    Method One:
    #!/bin/bash
    Red () {
    Echo-e "\033[41m \033[0m\c"
    }
    Yel () {
    Echo-e "\033[43m \033[0m\c"
    }
    Redyel () {
    For ((i=1;i<=4;i++));d o
    For ((j=1;j<=4;j++));d o
    ["$" = "-r"] && {yel;red;} | | {Red;yel;}
    Done
    Echo
    Done
    }

    For ((line=1;line<=8;line++));d o
    [$[$line%2]-eq 0] && Redyel | | Redyel-r
    Done

    Method Two:
    #!/bin/bash
    Lvse () {
    Echo-e "\e[1;42m \e[0m\c"
    }
    Huangse () {
    Echo-e "\e[1;43m \e[0m\c"
    }
    For i in {1..8};d o
    For x in {1..4};d o
    For n in {1..8};d o
    A= ' echo $[$[$i + $n]%2] '
    If [$a-eq 0];then
    Huangse
    Else
    Lvse
    Fi
    Done
    Echo
    Done
    Done



Second: The return value of the function
1:return
0 for correct results
1-255 is Error
2:exit

0 for correct results
1-255 is Error

Three: unset

Unset cancels the function definition, affecting only the current shell and its child shells.


Exercise 2:
Write a function to make the OS version judgment

Write a function that takes out the IP address of the current system eth0
Write functions for printing green OK and red failed
Write a function to determine if there are no positional parameters, such as no parameters, prompting for errors


Version () {
ver=$ (cat/etc/redhat-release | sed-r "s/.* ([0-9]) [.]. */\1/")

echo "Current version number is $ver"

return 0

}


IPAddr () {

ip=$ (IP a s | grep ens33 | sed-n "2p" | cut-d/-f1| awk ' {print $} ')
Echo $ip

return 0

}


Print_color () {
Echo-e "\033[41mfailed\033[0m"
Echo-e "\033[42mok\033[0m"
}


Judge_canshu () {

If [$#-eq 0];then
echo "Please enter at least one parameter"
Else
echo "A total of $# parameters"

Fi
}


Exercise 3

On CENTOS5 or 6, write the service script/etc/init.d/routed to complete the following requirements
(1) Script acceptable parameters: Start, stop, restart, status
(2) If the parameter is not one of these four, prompted to use the format after the error exit
(3) If start: Creates a/var/lock/subsys/routed and displays "OK"
Consider: If you have already started once, then show routed already runing ...
(4) If stop: delete/var/lock/subsys/script_name and show "OK"
Consider: "Faild" is displayed if it has already been stopped in advance
(5) If restart, stop first, then start
Consider: If there is no start, then the stop step shows "Faild", while the start step shows OK.
(6) If the/var/lock/subsys/script_name file exists, "routed is running ..." is displayed if the status is present.
If the/var/lock/subsys/script_name file does not exist, "routed is stopped ..." is displayed.
(7) Disable the start of the service in all modes, and can be managed with chkconfig and service commands
(8) When the script is start, routes to the 1.1.1.0 and 2.2.2.0 networks are configured on that host to go to 172.18.0.1.
(9) When the script is stop, two routes (8) are deleted
(10) When restart, the route is removed first, plus.

#!/bin/bash
# chkconfig:2345 19 80
# description:routed
if! [-d/var/lock/subsys];then
Mkdir-p/var/lock/subsys &>/dev/null
Fi
. /etc/init.d/functions

Start () {
if [-e/var/lock/subsys/routed];then
Action "Staring routed:routed already runing" false
Else
touch/var/lock/subsys/routed
Route add-net 1.1.1.0/24 GW 172.18.0.1
Route add-net 2.2.2.0/24 GW 172.18.0.1
Action "Starting routed:" True
Fi
}
Stop () {
if! [-e/var/lock/subsys/routed];then
Action "shutting down routed:routed not running" false
Else
rm-rf/var/lock/subsys/routed
Route del-net 1.1.1.0/24 GW 172.18.0.1
Route del-net 2.2.2.0/24 GW 172.18.0.1
Action "shutting down routed:" True
Fi
}
Status () {
if [-e/var/lock/subsys/routed];then
echo "Routed is running ..."
Else
echo "Routed is stopped ..."
Fi
}
Case $ in
Start
start;;
Stop
stop;;

Restart
Stop
start;;
Status
status;;
*)
echo "Usage: $ {Start|stop|status|restart}"
Esac


Exercise 4

Writing a script/root/bin/copycmd.sh
(1) Prompt the user to enter an executable command name
(2) Get a list of all library files that this command depends on
(3) Copy the command to a target directory (e.g./mnt/sysroot) under the corresponding path, such as:/bin/bash ==>/mnt/sysroot/bin/bash
/USR/BIN/PASSWD ==>/mnt/sysroot/usr/bin/passwd
(4) Copy all library files that this command relies on to the corresponding path under the target directory:/lib64/ld-linux-x86-64.so.2 ==>/mnt/sysroot/lib64/ld-linux-x86-64.so.2
(5) After each copy completes a command, do not exit, but prompt the user to type the new command to copy, and repeat the above functions; until user input quit quit
Cpcmd () {
CP ' which $1|tail-1 '/mnt/sysroot ' which $1|tail-1 ' &>/dev/null
LDD ' which $1|tail-1 ' |egrep-o "/lib64/.*" |sed-r ' [email protected]/lib64 (/.*). *@\[email protected] ' >/mnt/sysroot/ Test.txt
While Read line
Do
Cd/mnt/sysroot/lib64
If [-F $line];then
Continue
Else
Cp/lib64$line/mnt/sysroot/lib64$line &>/dev/null
Fi
Done </mnt/sysroot/test.txt
}

#!/bin/bash
. /root/bin/myfunctions
While True;do
Read-p "Please enter command:" cmd
Cpcmd $cmd
Done


Exercise 5:

Write a function to implement two numbers as parameters and return the maximum value

Max () {
If [$1-ge $];then
echo "Max is: $ $"
Else
echo "Max is: $"
Fi


Exercise 6:

The Fibonacci sequence is also called the Golden Division, because the mathematician Leonardo's Fibonacci to the rabbit breeding as an example, so called "Rabbit series", refers to such a series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 、......, the Fibonacci sequence is defined by the following recursive method: F (0) =0,f (1) =1,f (n) =f (n-1) +f (n-2), using functions to find the N-order Fibonacci sequence

Fei () {
        if [$1-eq 0];then
                 Let f$1=0
                 Echo $f $
        fi
        if [$1-eq 1];then
                 Let F$1=1
                 echo $f
        fi
         if [$1-gt 1];then
                 Echo $[$ (Fei $[$1-1]) +$ (Fei $[$1-2])
        Fi
}

#!/bin/bash
. /root/bin/myfunctions
For n in ' seq $ '
Do
Fei $n
Done


Exercise 7:
Hanoi (also known as Hanoi) is a story of an ancient Indian legend. When big Brahma created the world, he made three diamond pillars, and stacked 64 gold discs on a pillar from bottom to top in order of size. The great Brahma commanded the Brahman to rearrange the discs from below to the other pillars in order of size. It is also stipulated that the disk cannot be enlarged on the small disk, and only one disk can be moved at a time between the three pillars, using the function to realize the moving steps of the Hanoi of the N-disk.
Han () {
If [$1-eq 1];then
echo "$4"
Else
Han $[$1-1] $ $4
echo "$4"
Han $[$1-1] $ $4
Fi
}

#!/bin/bash
. /root/bin/myfunctions
Han $ ' A ' B ' C '

As you can see, exercise six, practice seven is recursive, and in the end we'll introduce what recursion is, and what the idea of recursion is.

First of all: there must be a way to exit the program, we also call it as a recursive export.

Second: Always try to simplify a problem to a smaller scale.

Finally: the parent and child issues cannot have overlapping parts

If these three points are met. We can use recursion to deal with the problem.


Shell Programming--function Chapter

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.