bash 导入shell脚本函数

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

Importing shell script function

bashshell

提问by Reuben

I have a function err()in file abc. The files do not have a .shextension, but they start with #!/bin/bash.

err()在 file 中有一个函数abc。这些文件没有.sh扩展名,但以#!/bin/bash.

err () {
    echo "" >&2 
}

Now I am importing it in a different file xyz:

现在我将它导入到另一个文件中xyz

source abc
someFunction(){ 
    err "Failed to back up"
}

Is this the right way of importing?

这是正确的导入方式吗?

回答by Sibi

Yes, you can do like you mentioned above or like: . FILENAME

是的,您可以像上面提到的那样或像: . FILENAME

The file need not to end with .sh

该文件不需要以 .sh

回答by cdarke

That's fine, here are some more hints:

没关系,这里还有一些提示:

  1. Use a naming convention for functions, for example prefix the function name with f_, for example f_err. Function calls appear no different as other commands, this is a hint to the reader. It also reduces the chances of a name collision.

  2. You need read access only, and you do not need the #!/bin/bash(its just a comment).

  3. In Bash, some options have to be set before function parsing. For example, shopt -s extglobhas to be done before and outside the function if it uses extended globbing. Putting that inside the function is too late.

  4. Bash does not support the FPATH environment variable or autoload (as Korn shell does).

  1. 使用函数的命名约定,例如在函数名称前加上f_,例如f_err。函数调用看起来与其他命令没有什么不同,这是对读者的一个提示。它还减少了名称冲突的机会。

  2. 您只需要读取访问权限,您不需要#!/bin/bash(它只是一个评论)。

  3. 在 Bash 中,必须在函数解析之前设置一些选项。例如,shopt -s extglob如果它使用扩展通配符,则必须在函数之前和之外完成。把它放在函数中为时已晚。

  4. Bash 不支持 FPATH 环境变量或自动加载(就像 Korn shell 那样)。

回答by techno

You need to exportnewly created functions

您需要导出新创建的函数

at end of abcadd this:

在末尾abc添加:

export -f err