简体   繁体   English

如何在两个shell脚本之间调用函数?

[英]How to invoke functions between two shell scripts?

I have functions to logInfo()/logError() in a shell script (logger.sh). 我在shell脚本(logger.sh)中具有logInfo()/logError()函数。 There are other shell scripts (example: createuser.sh) which require logging. 还有其他需要记录的shell脚本(例如:createuser.sh)。 How to invoke functions like logInfo() from createuser.sh 如何从createuser.sh调用logInfo()之类的函数

Without function invocations, these logInfo/logError functions are getting copied to every shell script that requires logging. 在没有函数调用的情况下,这些logInfo / logError函数将被复制到每个需要记录的shell脚本中。

Put your logger functions in a separate file (that only contains functions, no commands), say myfuncs.sh. 将您的记录器函数放在一个单独的文件中(该文件包含函数,不包含命令),例如myfuncs.sh。 Then in any other script that needs these functions, somewhere near the top of that script add a line: 然后在需要这些功能的任何其他脚本中,在该脚本顶部附近的某处添加一行:

. myfuncs.sh

or, equivalently: 或等效地:

source myfuncs.sh

The functions in myfuncs.sh will then be available in that script. 然后,myfuncs.sh中的功能将在该脚本中可用。

If the only thing in the logger.sh script is the functions (ie: nothing runsfid you execute it from the command line, then you can source the shell script by including the line: 如果logger.sh脚本中唯一的功能是函数(即:无任何运行,则可以从命令行执行它,然后可以通过添加以下行来获取Shell脚本的源代码:

. logger.sh

See: https://ss64.com/bash/source.html 请参阅: https//ss64.com/bash/source.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM