且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将参数传递给 Bash 函数

更新时间:2022-06-27 02:41:38

有两种典型的函数声明方式.我更喜欢第二种方法.

There are two typical ways of declaring a function. I prefer the second approach.

function function_name {
   command...
} 

function_name () {
   command...
} 

调用带参数的函数:

function_name "$arg1" "$arg2"

该函数通过它们的位置(而不是名称)来引用传递的参数,即 $1$2 等等.$0 是脚本本身的名称.

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

示例:

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.

输出:

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

参考:高级 Bash 脚本指南.