Bash:使用参数调用Function另一个脚本

时间:2016-11-24 13:39:01

标签: bash shell

初学者q: 如何在不同的脚本中调用函数并传递参数?

在下面的例子中,我想从TestAdd调用函数Add并将Var1和Var2作为参数传递...

脚本MatFuncs.sh

    function Add()
    {}
    function Subs()
    {}

脚本Ops.sh

    function TestAdd()
    {}
请尽可能详细。

3 个答案:

答案 0 :(得分:1)

您可以按如下方式编写Ops.sh:

source ./MatFuncs.sh

function TestAdd()
{
    Add var1 var2
}

答案 1 :(得分:0)

首先必须获取辅助文件,该文件将在您的上下文中执行,定义其功能。然后,您可以调用其他脚本的函数,就好像它们已在当前脚本中定义一样。

. /path/to/MatFuncs.sh             # source the file 
# source /path/fo/MathFuncs.sh     # a more verbose alternative
Add Var1 Var2                      # call its Add function with parameters

请注意,获取文件可能会产生副作用:如果我搜索的文件为cd,则我的当前目录将被更改。

您可以同时获取文件并在子shell中调用该函数,以便这些副作用不会影响您的主脚本,但最好的选择是确保您要获取的文件没有任何不必要的副作用

答案 2 :(得分:0)

  

我在不同的脚本中调用函数并传递参数?

不同的脚本就是这里的问题。实际上不同的脚本 充当您希望传递参数的函数的包装器。 考虑两个脚本:

<强>驱动器

#!/bin/bash
read -p "Enter two numbers a and b : " a b
# Well you should do sanitize the user inputs for legal values
./sum "$a" "$b"
# Now the above line is high octane part
# The "./" mentions that the "sum" script is in the same  folder as the driver
# The values we populated went in as parameters
# Mind the double quotes.If the actual input has spaces double quotes serves 
# to preserve theme
# We are all done for the driver part

<强>总和

#!/bin/bash
# The script acts as a wrapper for the function sum
# Here we calculate the sum of parameters passed to the script
function sum(){
(( sum = $1 + $2 ))
echo "Sum : $sum"
}
sum "$@" # Passing value from the shell script wrapper to the function
# $@ expands to the whole parameter input.
# What is special about "$@". Again, the spaces in the original parameters are preserved if those parameters were of the form "`A B"`.