初学者q: 如何在不同的脚本中调用函数并传递参数?Bash:调用带参数的函数另一个脚本
在下面的例子中,我想调用函数添加从TestAdd并通过VAR1和VAR2作为参数...
脚本MatFuncs.sh
function Add()
{}
function Subs()
{}
脚本Ops.sh
function TestAdd()
{}
please:尽可能详细。
初学者q: 如何在不同的脚本中调用函数并传递参数?Bash:调用带参数的函数另一个脚本
在下面的例子中,我想调用函数添加从TestAdd并通过VAR1和VAR2作为参数...
脚本MatFuncs.sh
function Add()
{}
function Subs()
{}
脚本Ops.sh
function TestAdd()
{}
please:尽可能详细。
您首先必须获取辅助文件,该文件将在您的上下文中执行它,并定义其功能。然后,您可以调用其他脚本的功能,就好像它们已在当前脚本中定义一样。
. /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中调用函数,以便这些副作用不会影响您的主脚本,但最好的选择是确保您想要的源文件没有任何不需要的一面影响。
可以如下写你Ops.sh:
source ./MatFuncs.sh
function TestAdd()
{
Add var1 var2
}
我调用函数不同的脚本和传递参数?
不同的脚本是在这里抓住。实际上,不同的脚本 充当您希望传递参数的函数的包装。 考虑两个脚本:
司机
#!/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 "[email protected]" # Passing value from the shell script wrapper to the function
# [email protected] expands to the whole parameter input.
# What is special about "[email protected]". Again, the spaces in the original parameters are preserved if those parameters were of the form "`A B"`.
和我怎么得到返回值? CC = TestAdd(){Add var1 var2} ?? – BigAlbert
请很好的例子如下: – Vijay
vijayn @维杰-DT:〜!$猫MatFuncs.sh #/斌/庆典 添加() { NUM1 = $ 1 NUM2 = $ 16 回报'EXPR $ NUM1 + $ #2# } vijayn @ vijay-dt:〜$ cat Ops.sh #!/ bin/sh 。 /家庭/ vijayn/MatFuncs。SH TestAdd() { 添加$ 1 $ 2 } TestAdd 10 15 总= $? echo $ total 希望这会有所帮助。 – Vijay