将参数传递给bash函数 [英] Passing parameters to a bash function

查看:174
本文介绍了将参数传递给bash函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图寻找如何通过在bash函数的参数,但事情的发生总是如何从命令行传递参数。

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.

我想我的脚本中传递参数。我想:

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 parameter to my function?

推荐答案

有声明一个函数的两种典型方式。我preFER第二种方法。

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

function function_name {
   command...
} 

function_name () {
   command...
} 

要调用一个函数的参数:

To call a function with arguments:

function_name $arg1 $arg2

的功能是指传递的参数由它们的位置(而不是由名称),即$ 1,$ 2,等等。 $ 1,0 是脚本本身的名称。

例如:

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

此外,您还需要调用现宣布后,你的函数的

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

#!/bin/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脚本编程指南

这篇关于将参数传递给bash函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆