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

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

1.定义函数

1
2
3
4
5
6
7
8
9
10
11
function fname()
{
   statements;
}
 
或者:
 
fname()
{
   statements;
}

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

例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[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.函数传参

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
[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

  

posted @   江戸川のコナン  阅读(1653)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
……
点击右上角即可分享
微信分享提示