Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

bash - 将参数传递给Bash函数(Passing parameters to a Bash function)

I am trying to search how to pass parameters in a Bash function, but what comes up is always how to pass parameter from the command line.

(我试图搜索如何在Bash函数中传递参数,但是出现的是如何从命令行传递参数。)

I would like to pass parameters within my script.

(我想在我的脚本中传递参数。)

I tried:

(我试过了:)

myBackupFunction("..", "...", "xx")

function myBackupFunction($directory, $options, $rootPassword) {
     ...
}

But the syntax is not correct, how to pass a parameter to my function?

(但是语法不正确,如何将参数传递给我的函数?)

  ask by stivlo translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are two typical ways of declaring a function.

(声明函数有两种典型方法。)

I prefer the second approach.

(我更喜欢第二种方法。)

function function_name {
   command...
} 

or

(要么)

function_name () {
   command...
} 

To call a function with arguments:

(要使用参数调用函数:)

function_name "$arg1" "$arg2"

The function refers to passed arguments by their position (not by name), that is $1, $2, and so forth.

(该函数引用通过其位置(而不是名称)传递的参数,即$ 1,$ 2等等。)

$0 is the name of the script itself.

($ 0是脚本本身的名称。)

Example:

(例:)

function_name () {
   echo "Parameter #1 is $1"
}

Also, you need to call your function after it is declared.

(此外,您需要声明调用您的函数。)

#!/usr/bin/env sh

foo 1  # this will fail because foo has not been declared yet.

foo() {
    echo "Parameter #1 is $1"
}

foo 2 # this will work.

Output:

(输出:)

./myScript.sh: line 2: foo: command not found
Parameter #1 is 2

Reference: Advanced Bash-Scripting Guide .

(参考:Advanced Bash-Scripting Guide 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...