Function of shell script 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

-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:-F    3,7 else echo "No such user." Fi}username=$1userinfousername=$2userinfo


Example 2: Service scripting framework

#!/bin/bash## chkconfig: - 50 50# description: test service script# prog=$ (basename $0) lockfile=/var/lock/subsys/$progstart ()  {    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&nbSP; " $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 $1 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 existsaddusers ()  {    if id $1  &> /dev/null; then        return 5     else        useradd $1         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."     fidone


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=tomsetname () {local name=jerry echo "Function: $name"}setnameecho "Shell: $name"

function recursion:

The function calls itself directly or indirectly;

Example: Implement the following functions

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]) F I}fact $


The following sequence is implemented:

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 $idoneecho


This article is from the "Wang Liming" blog, make sure to keep this source http://afterdawn.blog.51cto.com/7503144/1916045

Function of shell script 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.