shell 函数(特定的函数和脚本内传参)


和其他脚本语言一样,bash同样支持函数。我们可创建特定的函数,也可以创建能够接受参数的函数。需要的时候直接调用就可以了。

1.定义函数

function fname()
{
   statements;
}

或者:

fname()
{
   statements;
}

  只需要使用函数名,就可以调用某个函数

例如:

[root@gitlab script]# cat function_test.sh 
#!/bin/bash
function fname()
{
   echo "This is test function";              #;也可不用
} 

for i in {1..5}
do
  fname;                  #调用函数  ;也可不用
done
[root@gitlab script]# ./function_test.sh 
This is test function
This is test function
This is test function
This is test function
This is test function

  2.函数传参

[root@gitlab script]# cat function_test.sh 
#!/bin/bash
function fname()
{
   echo $1 $2          #打印参数
   echo "$@"           #以列表的方式一次性打印所有参数
   echo "$*"            #类似于$@,但单数被作为单个实体
}

fname hello world         #传参

echo "##########################"

fname 1 2 
[root@gitlab script]# ./function_test.sh 
hello world
hello world
hello world
##########################
1 2
1 2
1 2

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM