bash 函数可以在不同的脚本中使用吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1016404/
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-09 18:17:05  来源:igfitidea点击:

Can a bash function be used in different scripts?

bashfunction

提问by Herves

I've got a function that I want to reference and use across different scripts. Is there any way to do this? I don't want to be re-writing the same function for different scripts. Thanks.

我有一个要在不同脚本中引用和使用的函数。有没有办法做到这一点?我不想为不同的脚本重写相同的函数。谢谢。

回答by David Z

Sure - in your script, where you want to use the function, you can write a command like

当然 - 在你的脚本中,你想使用这个函数的地方,你可以写一个命令

source function.sh

which is equivalent to including the contents of function.shin the file at the point where the command is run. Note that function.shneeds to be in one of the directories in $PATH; if it's not, you need to specify an absolute path.

这相当于function.sh在命令运行的点将的内容包含在文件中。请注意,function.sh需要在$PATH;中的目录之一中。如果不是,则需要指定绝对路径。

回答by paxdiablo

Yes, you can localize all your functions in a common file (or files). This is exactly what I do with all my utility functions. I have a single utility.shincin my home directory that's used by all my programs with:

是的,您可以将所有函数本地化到一个公共文件(或多个文件)中。这正是我对所有实用功能所做的。utility.shinc我的主目录中有一个供我所有程序使用的单曲:

. $HOME/utility.shinc

which executes the script in the context of the current shell. This is important - if you simply run the include script, it will run in a subshell and any changes will not propagate to the current shell.

它在当前 shell 的上下文中执行脚本。这很重要 - 如果您只是运行包含脚本,它将在子 shell 中运行并且任何更改都不会传播到当前 shell。

You can do the same thing for groups of scripts. If it's part of a "product", I'd tend to put all the scripts, and any included scripts, in a single shell directory to ensure everything is localized.

您可以对脚本组执行相同的操作。如果它是“产品”的一部分,我倾向于将所有脚本和任何包含的脚本放在一个 shell 目录中,以确保所有内容都已本地化。

回答by Aliabbas Kothawala

Yes..you can! Add source function_namein your script. I prefer to create variable eg.VAR=$(funtion_name),if you add the source function_name after #!/bin/bash then your script first execute imported function task and then your current script task so its better to create variable and used anywhere in script. thank you..Hope its work for you:)

是的你可以!在脚本中添加source function_name。我更喜欢创建变量 eg.VAR=$(funtion_name),如果你在 #!/bin/bash 之后添加源函数名称,那么你的脚本首先执行导入的函数任务,然后是你当前的脚本任务,所以最好创建变量并在任何地方使用在脚本中。谢谢..希望它对你有用:)