Shell Programming - [04] function definitions, parameters, variable scope, library

definition

#!/bin/bash
#
# method one 
name1()
{
    echo "123"
}

# method two 
function name2
{
    echo "123"
}

function name3()
{
	echo 123
}
复制代码
  • Three methods can be
  • All later used herein are defined by function name { command.. }such a method

transfer

# call function by name
name1
# 123
name2
# 123
name3
# 123
复制代码

Exercise

  • Nginx using a function to determine whether the operation, if not running run nginx
#!/bin/bash
#

# if nginx is down, start it

function nginx_start
{
    # get pid
    pid=$$

    while true
    do
        ps -ef | grep nginx | grep -v grep | grep -v pid &> /dev/null
        status=$?
        if [ "$status" -eq 0 ] ; then
            echo "Nginx is running well."
        else
            systemctl start nginx
            echo "Nginx is down, start it...."
        fi
        sleep 3
    done
}
# 如果这里不调用执行sh 命令是没有任何结果的。需要执行了sh后再执行nginx_start
nginx_start

复制代码

About $ special supplement usage of:

  • $ # Number of arguments passed to the script
  • $ * Displays all parameters passed to the script to a single string
  • The script runs the current process ID number
  • @ versus* The same, but the use of quotation marks, and returns each parameter in quotation marks.
  • $ - Shell used in the current display options, and set the same command function.
  • $? Exit status display last command. 0 means no error, any other value indicates an error

Function parameters

  • Arguments do not like the other programming languages ​​tangible parameters
  • Function parameters can be used directly in the $ 2 $ 1 the function 3 ...n
  • In use $(( ))to do calculations, be sure to add $symbols

usage

#!/bin/bash
#

function params
{
    echo "hello $1"
    echo "hello $2"
    echo "hello $3"
}
复制代码
  • transfer
params params1 params2 123
# hello params1
# hello params2
# hello 123
复制代码

case

Simple calculator to achieve

#!/bin/bash
#

# a simple calculator

function calculator
{
    case $2 in 
        +)
            echo "`expr $1 + $3`"
            ;;
        -)
            echo "`expr $1 - $3`"
            ;;
        \*)
            echo "`expr $1 \* $3`"
            ;;
        /)
            echo "`expr $1 / $3`"
            ;;
    esac
}
复制代码

For the use case of

casein
匹配值1)
    command1
    command2
    ...
    commandN
    ;;
匹配值2)
    command1
    command2
    ...
    commandN
    ;;
esac
复制代码

Again: this sh need to file and then use the following command in the command line.

transfer

calculator 12 + 3
# 15
calculator 12 - 3
# 9
calculator 12 * 3
# 36
calculator 12 / 3
# 4
复制代码

Function return value

  • Return value of the function can return echo and two methods
  • Usually do return code back behind the range 1-255 with the default number is not 0
  • As a result value is returned echo, generally may be printed directly as a result of the terminal returns a string with the list, number, etc.

Case

01 represent return run and not run Nginx

#!/bin/bash
#

# judge nginx was running

function is_nginx_running
{
    pid=$$

    ps -ef | grep nginx | grep -v grep &> /dev/null

    status=`echo $?`

    if [ $status -eq 0 ] ; then
        # 默认返回0
        return 
    else
        return 1
    fi
}
复制代码

transfer

is_nginx_running && echo "Ningx is running" || ehco "Ningx is Stop"
# Ningx is running
复制代码

Get all of the user's system

#!/bin/bash
#

# get all username

function get_users
{
    users=`cat /etc/passwd | cut -d : -f1`
    echo $users
}

# echo all users name
users=`get_users`
index=1
for s in $users
do
    echo "The $index user  is $s."
    index=$(($index+1))
done

复制代码

Variable scope

  • In the shell if not specifically stated, the variable whether it is outside the body of the function or function are global variables
  • If you want to use local variables within the function requires the use of localkeywords
  • Prudent use of global variables.
  • Function does not run the function body global variables defined functions or other internal functions to access external invalid.

case

#!/bin/bash
#
var1="hello world"

function test1
{
    var2=123
}

function test2
{
    local var3="local variable"
    echo $var2
}

function test3
{
    echo $var3
}


# 测试

echo $var1 $var2 $var3
# hello world 
test1
test2
test3
echo $var1 $var2 $var3
# hello world 123

复制代码

Library

  • We can form our library by defining some common function or a function of relatively high reusability

Math library definitions and display system information: Case

# add reduce multiple divide sys_load
function add
{
    echo "`expr $1 + $2`"
}

function reduce
{
    echo "$(($1 - $2))"
}

function multiple
{
    echo "`expr $1 \* $2`"
}

function divide
{
    echo "$(($1 / $2))"
}

function sys_load
{
    echo "Memory Info : "
    echo 
    free -m
    echo 

    echo "Disk Usage"
    echo
    df -h
    echo
}
复制代码

Use library

  • We need to load the library and then use
  • Load the library can be used .or sourceboth methods
  • No library file name suffix, but here suggest that you use lib easy to distinguish. Of course, can not file extension
#!/bin/bash
#
source ./lib/mylib.lib
# . ./lib/mylib.lib
add 1 2
reduce 2 1
multiple 2 2 
divide 12 3

sys_load
复制代码
  • result
3
1
4
4
Memory Info : 

              total        used        free      shared  buff/cache   available
Mem:           1838        1003          89           0         746         645
Swap:             0           0           0

Disk Usage

文件系统        容量  已用  可用 已用% 挂载点
/dev/vda1        40G   16G   22G   42% /
devtmpfs        908M     0  908M    0% /dev
tmpfs           920M  4.0K  920M    1% /dev/shm
tmpfs           920M  580K  919M    1% /run
tmpfs           920M     0  920M    0% /sys/fs/cgroup
tmpfs           184M     0  184M    0% /run/user/0

复制代码

Reproduced in: https: //juejin.im/post/5d050a816fb9a07edf274260

Guess you like

Origin blog.csdn.net/weixin_33805557/article/details/93182386