Day4:Shell 函数编程

Shell 函数的本质是一段可以重复使用的脚本代码,这段代码被提前编写好的,然后放在指定位置,使用时直接调用即可。

如果学过Python的话,这个真的看起来很简单。

1、定义函数

  • 可以带function fun()定义,也可以直接用fun()定义,不带任何参数。
#方法一
function name {
    commands
    [return value]
}
#方法二
name() {
    commands
    [return value]
}
  • function 是Shell中的挂件自,专门用来定义函数;
  • name是函数名;
  • return value 表示函数的返回值,其中return 是Shell关键字,专门用再函数中返回值;这一部分可以写也可以不写。
  • 由{ }包围的部分称为函数体,调用一个函数,实际上就是直行函数中的代码。
  • 函数的优势
    • 方便多次使用,减少代码量,使用方便,整洁
    • 当需要修改里面的重复代码时,只需要修改一次函数即可实现需求;
    • 将函数写入文件,需要时直接通过文件调用。

 2、调用函数

1、执行不带参数的函数

  • 直接输入函数名即可,不需要带括号。 functionName
  • 执行函数时,函数名前的关键字function和函数名后面的()均不需要带
  • 函数的定义必须在执行程序前定义或加载

2、执行带参数的函数

  • functionName arg1 arg2
  • Shell 中的位置参数(1/2../)?/¥@均可以作为函数参数进行传递
  • $0比较特殊,仍然是父脚本的名称
  • 此时父脚本的参数会临时被函数的参数所覆盖或隐藏
  • 函数的参数变量是再函数体里面定义的

3、函数的执行总结

  • shell中各种程序的执行顺序为:系统别名->函数->系统命令->可执行文件等
  • 函数执行时,会和调用它的脚本共享变量,也可以为函数设定局部变量及特殊位置参数
  • 在Shell函数里面,return和exit功能类似,区别是return是退出函数,exit则是退出脚本
  • exit则会返回一个值给执行当前脚本的Shell
  • 如果将函数单独存放为一个文件,在加载时需要使用source或 . 进行加载
  • 在函数内部一般使用local定义局部变量,仅在函数体内有效

4、调用函数

[root@locahost ~]# cat testfunction.sh
#!/bin/bash

# first function
function HelloWorld() {
    echo "Hello world"
}


# second function

Welcome() {
    echo "Welcome to beijing"
}


# third function

function HelloShell {

    echo "Hello Shell"
}

# 调用函数
HelloWorld 
Welcome
HelloShell
[root@locahost ~]# bash testfunction.sh
Hello world
Welcome to beijing
Hello Shell
实例

5、在文件中调用函数

[root@locahost ~]# cat filefunction.sh
function Sum () {
    for((i=1;i<=100;i++))
    do
        ((sum=sum+i))
    done
    echo '{1..100} sum is :' $sum
}

[root@locahost ~]# cat filefunctionfromfile.sh
#!/bin/bash
path="/root/Test/filefunction.sh"
if [ ‐f ${path} ]
then
    source $path # 加载函数
    Sum # 调用函数
else
    echo "file not exist or error"
fi
[root@locahost ~]# bash filefunctionfromfile.sh
{1..100} sum is : 5050
实例

3、函数参数的传递

[root@locahost ~]# cat functionwithargs.sh
#!/bin/bash
# 定义函数
function Add () { 
    ((sum=$1+$2))
    echo "$1 + $2 sum is" ${sum}
}
Add $1 $2 # 调用函数并传递参数
[root@locahost ~]# bash functionwithargs.sh 100 150
100 + 150 sum is 250
[root@locahost ~]# bash functionwithargs.sh 509 150
509 + 150 sum is 659
实例

4、return返回函数的结果

[root@locahost ~]# cat functionwithreturn.sh
#!/bin/bash
function TestReturn() {
if [ ‐d $1 ]
then
    return "122"
else
    return "222"
fi
}

TestReturn $1

result=$? # 获取函数返回值
if [ ${result} == "122" ]
then
    echo "$1 exist ,return value is:" ${result}
else
    echo "$1 not exist ,return value is:" ${result}
fi
[root@locahost ~]# bash functionwithreturn.sh /etc/sysconfiggg
/etc/sysconfiggg not exist ,return value is: 222
[root@locahost ~]# bash functionwithreturn.sh /etc/sysconfig
/etc/sysconfig exist ,return value is: 122
实例

5、echo返回函数结果

[root@locahost ~]# cat functionwithecho.sh
#!/bin/bash
function TestReturn() {
if [ ‐d $1 ]
then
    echo "122"
else
    echo "222"
fi
}
result=$(TestReturn $1) # 获取函数返回值
if [ ${result} == "122" ]
then
    echo "$1 exist ,return value is:" ${result}
else
    echo "$1 not exist ,return value is:" ${result}
fi
[root@locahost ~]# bash functionwithecho.sh /etc/sysconfig
/etc/sysconfig exist ,return value is: 122
[root@locahost ~]# bash functionwithecho.sh /etc/sysconfiggg
/etc/sysconfiggg not exist ,return value is: 222
实例

在该示例中,主要使用 $() 获取返回值,在该方法中,没有范围限制,是一种比较安全的返回方式。

[root@qfedu.com ~]# cat functionwithecho.sh
#!/bin/bash
function TestReturn() {
if [ ‐d $1 ]
then
    echo "$1 exist"
else
    echo "$1 not exist"
fi
}
result=$(TestReturn $1) # 获取返回值,返回的结果是字符串
if [ "${result}" == "$1 exist" ]
then
    echo "$1 exist ,return value is:" ${result}
else
    echo "$1 not exist ,return value is:" ${result}
fi
[root@qfedu.com ~]# bash functionwithecho.sh /etc/sysconfiggg
/etc/sysconfiggg not exist ,return value is: /etc/sysconfiggg not exist
[root@qfedu.com ~]# bash functionwithecho.sh /etc/sysconfig
/etc/sysconfig exist ,return value is: /etc/sysconfig exist
实例

6、全局变量和局部变量

[root@locahost ~]# cat test3.sh
function fun() {
    a=$[ $b + 5 ]
    c=$[ $a * 2 ]
}
a=4
b=6
fun
if [ $a ‐gt $b ]
then
    echo "$a is larger than $b"
else
    echo "$a is smaller than $b"
fi
function fun() {
    local a=$[ $b + 5 ]
    c=$[ $a * 2 ]
}
a=4
b=6
fun
if [ $a ‐gt $b ]
then
    echo "$a is larger than $b"
else
    echo "$a is smaller than $b"
fi
[root@locahost ~]# bash test3.sh
11 is larger than 6
4 is smaller than 6
实例

7、属租变量和函数

  • $@ 变量会单独处理每个参数
[root@locahost ~]# cat test4.sh
function addarray() {
    local sum=0
    local newarray
    newarray=($(echo "$@"))
for value in ${newarray[*]}
do
    sum=$[ $sum + $value ]
done
echo $sum
}
myarray=(1 2 3 4 5)
# 这里 arg1=${myarray[*]} 也可以

arg1=$(echo ${myarray[*]})
result=$(addarray $arg1)
echo "The result is $result"

[root@locahost ~]# bash test4.sh
The result is 15
[root@locahost ~]# cat test5.sh
function arraydblr() {
    local origarray
    local newarray
    local elements
    local i
    origarray=($(echo "$@"))
    newarray=($(echo "$@"))
    elements=$[ $# ‐1 ]
    for (( i = 0; i <= $elements; i++))
    {
    newarray[$i]=$[ ${origarray[$i]} * 2 ]
    }
    echo ${newarray[*]}
}
myarray=(1 2 3 4 5)
arg1=$(echo ${myarray[*]})
result=($(arraydblr $arg1))
echo "The new array is: ${result[*]}"
[root@locahost ~]# cat test4.sh bash test5.sh
The new array is: 2 4 6 8 10
实例

8、递归函数

[root@locahost ~]# cat test6.sh
function factorial() {
    if [ $1 ‐eq 1 ]
    then
        echo 1
    else
        local temp=$[ $1 ‐ 1 ]
        local result=$(factorial $temp)
        echo $[ $result * $1 ]
    fi
}
read ‐p "Enter value: " value
result=$(factorial $value)
echo "The factorial of $value is: $result"
[root@locahost ~]# bash test6.sh
Enter value: 5
The factorial of 5 is: 120
View Code

 

posted on 2021-02-10 22:27  超nmmmmm  阅读(86)  评论(0编辑  收藏  举报

导航