linux shell 自定义函数方法(定义、返回值、变量作用域)

(编辑:jimmy 日期: 2024/9/21 浏览:2)

一、定义shell函数(define function)

语法:

[ function ] funname [()]
{
action;
[return int;]
}

说明:

1、可以带function fun() 定义,也可以直接fun() 定义,不带任何参数。
2、参数返回,可以显示加:return 返回,如果不加,将以最后一条命令运行结果,作为返回值。 return后跟数值n(0-255

实例(testfun1.sh):

#!/bin/sh 
  
 fSum 3 2; 
 function fSum() 
 { 
   echo $1,$2; 
   return $(($1+$2)); 
 } 
 fSum 5 7; 
 total=$(fSum 3 2); 
 echo $total,$"htmlcode">
#!/bin/sh 
 
echo $(uname); 
declare num=1000; 
 
uname() 
{ 
  echo "test!"; 
  ((num++)); 
  return 100; 
} 
testvar() 
{ 
  local num=10; 
  ((num++)); 
  echo $num; 
 
} 
 
uname; 
echo $"color: #ff0000">以下是其它网友的补充:

本教程目前为止所有脚本都是从头到尾执行。这样做很好,但你也许已经注意到有些脚本段间互相重复。

shell允许将一组命令集或语句形成一个可用块,这些块称为shell函数。

shell中函数的定义格式如下:

函数名(){
command1
command2
...
commandN
[ return value ]
}

如果愿意,可在函数名前加上关键字function,这取决于使用者。
function 函数名(){
command1
command2
...
commandN
[ return value ]
}

函数返回值,可以显示增加return语句;如果不加,则将最后一条命令运行结果作为返回值(一般为0,如果执行失败则返回错误代码)。 return后跟数值(0-255)。

函数可以放在同一个文件中作为一段代码,也可以放在只包含函数的单独文件中。函数不必包含很多语句或命令,甚至可以只包含一个echo语句,这取决于使用者。

下面的例子定义了一个函数并进行调用:

#!/bin/bash
demoFun(){
echo "This is your first shell function!"
}
echo "Function begin..."
hello
echo "Function end!"输出:
Function begin...
This is your first shell function!
Function end!

下面定义一个带有return语句的函数:

#!/bin/bash
funWithReturn(){
echo "The function is to get the sum of two numbers..."
echo -n "Input first number: "
read aNum
echo -n "Input another number: "
read anotherNum
echo "The two numbers are $aNum and $anotherNum !"
return $(($aNum+$anotherNum))
}
funWithReturn
echo "The sum of two numbers is $"输出类似下面:
The function is to get the sum of two numbers...
Input first number: 25
Input another number: 50
The two numbers are 25 and 50 !
The sum of two numbers is 75 !

函数返回值在调用该函数后通过 $? 来获得。

注意:所有函数在使用前必须定义。这意味着必须将函数放在脚本开始部分,直至shell解释器首次发现它时,才可以使用。调用函数仅使用其函数名即可。

一句话新闻

微软与英特尔等合作伙伴联合定义“AI PC”:键盘需配有Copilot物理按键
几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。