shell脚本--函数

  shell的函数和Javacript和php的函数声明一样,只不过shell在调用函数的时候,只需要写函数名就可以调用函数,注意不要在函数名后面加括号

  

创建并使用函数

#!/bin/bash
#文件名:test.sh

function test(){
    echo "aaaaaaa"
}
#直接使用函数名就可以调用函数
test
test

  运行:

ubuntu@ubuntu:~$ ./test.sh
aaaaaaa
aaaaaaa
ubuntu@ubuntu:~$ 

  

函数传参、局部变量

  给函数传递参数的方法 和给运行脚本传参数的方法相同:写在调用的函数名后面,空格分隔。

  使用$1表示第一个参数,$#获取所有参数的个数,$*获取所有参数

  shell中,默认在脚本任何地方定义的变量都是全局变量,但是可以再函数中使用local限定为局部变量,只在本函数中有效。

#!/bin/bash
#文件名:test.sh

#求0到num的和
function sum(){
    local num=$1
    local tot=0
    local i=0
    while [ $i -le $num ];do
        tot=$[ $tot + $i ]
        i=$[ $i + 1 ]
    done

    echo $tot
}

res=$(sum 100)
echo "0+1+2+...+100="$res

  运行:

ubuntu@ubuntu:~$ ./test.sh
0+1+2+...+100=5050
ubuntu@ubuntu:~$ 

  

给函数传递数组(在函数中复制数组)

  使用的是$*访问传递的所有数组元素,所以在传递给函数数组时,不要只写数组名,应该写为${arr[*]}才是将数组所有元素传递。

  在函数内部使用()将$*括起来,此时就类似于将数组元素展开到()中,然后赋值给一个变量。

#!/bin/bash

arr=("one" "two" "three")
function show(){
    #create a new array
    local arr=($*)
    arr[0]="opq";arr[1]="rst";arr[2]="xyz"
    echo ${arr[*]} ${#arr[*]}
}

echo ${arr[*]} ${#arr[*]}
show ${arr[*]}
echo ${arr[*]} ${#arr[*]}

  运行结果:

ubuntu@ubuntu:~$ ./test.sh
one two three 3
opq rst xyz 3
one two three 3

  

函数返回数组

#!/bin/bash

function return_arr(){
    local arr=("one" "two" "three")
    echo ${arr[*]}
}

#注意格式,是在返回值的外边加一层括号
res=($(return_arr))
echo ${#res} ${res[*]}

  

原文地址:https://www.cnblogs.com/-beyond/p/8280208.html