Linux 如何在 bash shell 脚本中包含文件

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

How to include file in a bash shell script

linuxbashinclude

提问by Mechaflash

Is there a way to include another shell script in a shell script to be able to access its functions?

有没有办法在 shell 脚本中包含另一个 shell 脚本以便能够访问它的功能?

Like how in PHP you can use the includedirective with other PHP files in order to run the functions that are contained within simply by calling the function name.

就像在 PHP 中一样,您可以将include指令与其他 PHP 文件一起使用,以便通过调用函数名称来运行其中包含的函数。

采纳答案by Gilles Quenot

Simply put inside your script :

只需放入您的脚本中:

source FILE

Or

或者

. FILE

it's the same thing.

这是同一件事。

$ LANG=C help source
source: source filename [arguments]
Execute commands from a file in the current shell.

Read and execute commands from FILENAME in the current shell.  The
entries in $PATH are used to find the directory containing FILENAME.
If any ARGUMENTS are supplied, they become the positional parameters
when FILENAME is executed.

Exit Status:
Returns the status of the last command executed in FILENAME; fails if
FILENAME cannot be read.

回答by Paul

Yes, use sourceor the short form which is just .:

是的,使用源代码或简写形式.

. other_script.sh

回答by Fancyoung

Above answers are correct, but if run script in other folder, there will be some problem.

以上答案是正确的,但如果在其他文件夹中运行脚本,则会出现一些问题。

For example, the a.shand b.share in same folder, a include b with . ./b.shto include.

例如,a.shb.sh在同一个文件夹中,a 包含 b 与 . ./b.sh包含。

When run script out of the folder, for example with xx/xx/xx/a.sh, file b.shwill not found: ./b.sh: No such file or directory.

当在文件夹外运行脚本时,例如使用xx/xx/xx/a.shb.sh将找不到文件:./b.sh: No such file or directory

I use

我用

. $(dirname "
. ./color.sh
")/b.sh

回答by Raf

In my situation, in order to include color.shfrom the same directory in init.sh, I had to do something as follows.

在我的情况下,为了color.sh从 中的同一目录包含init.sh,我必须执行以下操作。

RED=`tput setaf 1`
GREEN=`tput setaf 2`
BLUE=`tput setaf 4`
BOLD=`tput bold`
RESET=`tput sgr0`

Not sure why the ./and not color.shdirectly. The content of color.shis as follows.

不知道为什么,./而不是color.sh直接。内容color.sh如下。

##代码##

Making use of File color.shdoes not error but, the color do not display. I have tested this in Ubuntu 18.04and the Bashversion is:

使用File color.sh不报错,颜色不显示。我已经测试过了Ubuntu 18.04Bash版本是:

GNU bash, version 4.4.19(1)-release (x86_64-pc-linux-gnu)

GNU bash, version 4.4.19(1)-release (x86_64-pc-linux-gnu)