如何定义在任何脚本中使用的 bash 函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6218268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:06:30  来源:igfitidea点击:

How to define a bash function for use in any script?

bashfunctionexport

提问by grok12

I'd like to define it once and use it anywhere.

我想定义一次并在任何地方使用它。

采纳答案by Jay

While i basically agree with eduffy, i typically put such functions in a file either in the user's home directory or if the scripts are shared between users in a directory in the user's path. I would then source the file (. ~/FILE or . $(type -p FILE)) in the .bash_profile. This allows you to 're-source' the file if necessary (i.e., you change something in it) w/o having to re-login, etc.

虽然我基本上同意 eduffy,但我通常将这些函数放在用户主目录中的文件中,或者如果脚本在用户路径中的目录中的用户之间共享。然后我会在 .bash_profile 中获取文件(. ~/FILE 或 . $(type -p FILE))。这允许您在必要时“重新获取”文件(即,您更改其中的某些内容)而不必重新登录等。

回答by Amir Afghani

In bash, you can run sourcefrom your script (with the file containing your functions as the argument) and simply call the function. This is what happens implicitly when you define the function in your .bashrcfile.

在 bash 中,您可以source从您的脚本运行(使用包含您的函数的文件作为参数)并简单地调用该函数。这是在.bashrc文件中定义函数时隐式发生的情况。

回答by barti_ddu

Place your "common" function in a separate script (let's call it "a"):

将您的“通用”函数放在一个单独的脚本中(我们称之为“a”):

#!/bin/bash

test_fun () {
    echo "hi"
}

Next, "import" it into another script (say, "b"):

接下来,将它“导入”到另一个脚本中(比如“b”):

#!/bin/bash

. ./a

test_fun

Running bash bwill output "hi"

运行bash b会输出“hi”

回答by eduffy

Put it in your ~/.bashrcor ~/.bash_profile.

把它放在你的~/.bashrc~/.bash_profile.