2016-11-24 25 views
-1

初心者q: 別のスクリプトで関数を呼び出し、パラメータを渡すにはどうすればよいですか?次の例ではBash:パラメータを持つ関数を呼び出す別のスクリプト

、私はTestAddから追加のparamsとしてVAR1とVAR2を渡す関数を呼び出すしたいと思います...

スクリプトMatFuncs.sh

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

スクリプトOps.sh

function TestAdd() 
    {} 

お願い:できるだけ詳しくお伝えください。

答えて

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を行い、ファイルをソースならば、私の現在のディレクトリが変更されています。

これらの副作用がメインスクリプトに影響しないように、ソースファイルとサブシェルで関数を呼び出すことができますが、最適な方法は、ソースファイルに不要な側がないことを確認することです効果。

1

あなたは以下のようにあなたのOps.shを書き込むことができます。

source ./MatFuncs.sh 

function TestAdd() 
{ 
    Add var1 var2 
} 
+0

とどのように私は、戻り値を取得します: 2つのスクリプトを考えてみましょうか? CC = TestAdd(){Add var1 var2} ?? – BigAlbert

+0

例の下に罰金してください: – Vijay

+0

vijayn @のビジェイ-DT:!〜$猫MatFuncs.sh #/ binに/ bashのを 追加() { NUM1 = $ 1 からnum2 = $ 2 リターン 'exprの$ NUM1 + $ num2' } vijayn @ vijay-dt:〜$ cat Ops.sh #!/ bin/sh 。/home/vijayn/MatFuncs。SH TestAdd() TestAdd 10 15 合計= $ { は$ 1 $ 2 を追加しますか}? echo $ total これは役立ちます。 – Vijay

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 "[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"`. 
関連する問題