linux shell中创建函数
001、
[root@pc1 test]# cat test.sh ## 函数脚本 #!/bin/bash function db1 ## function关键字来定义函数,db1是函数名 { read -p "请输入:" value return $[$value *2] ## return返回函数值 } db1 ## 函数调用 echo $?
[root@pc1 test]# bash test.sh ## 在脚本中运行函数 请输入:45 90
002、
[root@pc1 test]# ls test.sh [root@pc1 test]# cat test.sh ## 修改上面的函数脚本 #!/bin/bash function db1 { read -p "请输入:" value echo $[$value *2] ## 将return改为了echo } db1 ## echo $? ## 函数返回值可以省略该句
调用测试:
[root@pc1 test]# ls test.sh [root@pc1 test]# cat test.sh ## 函数脚本 #!/bin/bash function db1 { read -p "请输入:" value echo $[$value *2] } db1 ## echo $? [root@pc1 test]# bash test.sh ## 执行脚本 请输入:45 90
003、
[root@pc1 test]# ls test.sh [root@pc1 test]# cat test.sh ## 函数脚本 #!/bin/bash function db1() ## 定义函数名时,在函数名后面增加小括号,不影响函数的调用 { read -p "请输入:" value echo $[$value *2] } db1
[root@pc1 test]# ls test.sh [root@pc1 test]# cat test.sh ## 脚本 #!/bin/bash function db1() { read -p "请输入:" value echo $[$value *2] } db1 [root@pc1 test]# bash test.sh ## 执行 请输入:47 94
004、小括号的作用
01、有关键字function的情况下,函数名后面可以又括号,也可以无括号
02、无关键字funtion的情况下, 函数名后面必须有括号
a、有fuancion情况
[root@pc1 test]# ls │[root@pc1 test]# ls 001.sh 002.sh │001.sh 002.sh [root@pc1 test]# cat 001.sh │[root@pc1 test]# cat 002.sh #/bin/bash │#/bin/bash │ function db1() │function db1 { │{ value=10 │ value=10 echo $[$value *2] │ echo $[$value *2] } │} │ db1 │db1 [root@pc1 test]# │[root@pc1 test]#
两者多函数的使用没有影响:
b、无function的情况
002.sh相对于001.sh,函数名后边少了小括号, 其余都一样:
执行效果:
以上说明在又function的情况下, 函数名后面有无括号对函数的使用没有影响;
在无function的情况下,函数名后面无小括号将无法正常调用。
005、函数的传参
[root@pc1 test]# ls 001.sh [root@pc1 test]# cat 001.sh ## 测试函数 #/bin/bash function db1() { value=$(($1 + $2)) ## $1 和 $2分别代表位置参数1和位置参数2 echo $[$value *2] } db1 $1 $2 ## 调用函数时,需要标明位置参数 [root@pc1 test]# bash 001.sh 3 4 ## 执行脚本,给与位置参数1值和位置参数2值 14
。
参考:
01、https://blog.csdn.net/datangda/article/details/130556349