Function of Shell programming

Source: Internet
Author: User
Tags variable scope

Functions: function

Program Programming: Code Reuse

Modular programming

Structured programming

The code of an independent function as a whole, and a name for it; a named code snippet, which is a function;

Note: The code snippet that defines the function is not executed automatically and is executed at call time;

Any location where the function name appears, is automatically replaced with the function code when the code executes;

Syntax One:

function F_name {

... function Body ...

}

Syntax Two:

F_name () {

... function Body ...

}

The life cycle of a function: created every time it is called, terminates when returned;

Its status returns the result of the state of the last command running in the function body;

To customize the status return value, you need to use: return

return [0-255]

0: Success

1-255: Failure

Example: Given a user name, get the ID number of the user and the default shell;

#!/bin/bash

#


UserInfo () {

If ID "$username" &>/dev/null; Then

grep "^ $username \>"/etc/passwd | Cut-d:-f3,7

Else

echo "No such user."

Fi

}


Username=$1

UserInfo


Username=$2

UserInfo

Example 2: Service scripting framework

#!/bin/bash

#

# Chkconfig:-50 50

# description:test Service Script

#

prog=$ (basename)

lockfile=/var/lock/subsys/$prog


Start () {

If [-f $lockfile]; Then

echo "$prog is running yet."

Else

Touch $lockfile

[$?-eq 0] && echo "Start $prog finshed."

Fi

}


Stop () {

If [-f $lockfile]; Then

Rm-f $lockfile

[$?-eq 0] && echo "Stop $prog finished."

Else

echo "$prog is not running."

Fi

}

Status () {

If [-f $lockfile]; Then

echo "$prog is running"

Else

echo "$prog is stopped."

Fi

}


Usage () {

echo "Usage: $prog {start|stop|restart|status}"

}


Case $ in

Start

start;;

Stop

stop;;

Restart

Stop

start;;

Status

status;;

*)

Usage

Exit 1;;

Esac

function return value:

The return value of the function's execution result:

(1) using the Echo or printf command to output;

(2) The execution result of the command called in the function body;

Exit status code for the function:

(1) The default depends on the exit status code of the last command executed in the function body;

(2) Custom: Return

The function can accept parameters:

Pass parameters to the function:

In the function body, you can use $1,$2, ... A reference to a parameter passed to a function; You can also use $* or [email protected] in a function to reference all parameters, $ #引用传递的参数的个数;

When calling a function, the given argument list is separated by a whitespace character after the function name, for example, TestFunc arg1 arg2 arg3 ...

Example: Add 10 users,

Add the user's function using function implementation, user name as parameters passed to the function;

#!/bin/bash

#

# 5:user exists


AddUsers () {

If ID $ &>/dev/null; Then

Return 5

Else

Useradd $

Retval=$?

Return $retval

Fi

}


For i in {1..10}; Do

AddUsers ${1}${i}

Retval=$?

If [$retval-eq 0]; Then

echo "ADD user ${1}${i} finished."

elif [$retval-eq 5]; Then

echo "User ${1}${i} exists."

Else

echo "Unkown Error."

Fi

Done

Exercise: Write a script;

Use the function to ping a host to test the host's online status, and the host address is passed to the function via parameters;

Main program: Test the online status of each host in the 172.16.1.1-172.16.67.1 range;

Exercise: Write a script;

Print the nn multiplication table;

Variable scope:

Local variables: The scope is the life cycle of the function, and is automatically destroyed at the end of the function;

Methods for defining local variables: local variable=value

Local variable: The scope is the life cycle of the shell process that runs the script, so its scope is the current shell script file;

Sample program:

#!/bin/bash

#

Name=tom


SetName () {

Local Name=jerry

echo "Function: $name"

}


SetName

echo "Shell: $name"

function recursion:

The function calls itself directly or indirectly;

10!=10*9!=10*9*8!=10*9*8*7!= ...

N

N (n-1)!=n* (n-1) * (n-2)! =


#!/bin/bash

#

Fact () {

If [$1-eq 0-o $1-eq 1]; Then

Echo 1

Else

echo $[$1*$ (fact $[$1-1])

Fi

}


Fact $

1,1,2,3,5,8,13,21,...

#!/bin/bash

#

Fab () {

If [$1-eq 1]; Then

Echo-n "1"

elif [$1-eq 2]; Then

Echo-n "1"

Else

Echo-n "$[$ (Fab $[$1-1]) +$ (Fab $[$1-2])]"

Fi

}


For I in $ (seq 1 $); Do

Fab $i

Done

Echo


Function of Shell programming

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.