源作者:码享客
shell运行c语言程序
shell中调用其他shell脚本中的函数
类似于C语言等高级语言,可以在一个shell脚本中定义函数,然后在另一个shell脚本中调用这个函数。不过,使用的时候需要使用
source命令
(有的时候也可以用点操作符),类似于C语言的include头文件或者extern声明一样。举例如下,首先建立被调用的shell脚本,命名为itertion.sh,n内容如下:
#/bin/bash
function iter {
if [ $1 -eq 1 ];then
echo 1
else
local tmp=$[ $1 - 1 ]
local result=$(iter $tmp)
echo $[ $1 * $result ]
fi
}
这个脚本中有一个函数,函数名为
iter
,这个函数会对输入的数字求阶乘。然后,建立另外一个脚本如下,在脚本中使用
source
命令,加载itertion.sh脚本。
#/bin/bash
source https://www.whysem.com/a/itertion.sh
value=5
res=$(iter $value)
echo "res=$res"
运行后,输出的结果为:
res=120