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
How to include file in a bash shell script
提问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 include
directive 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 Fancyoung
Above answers are correct, but if run script in other folder, there will be some problem.
以上答案是正确的,但如果在其他文件夹中运行脚本,则会出现一些问题。
For example, the a.sh
and b.sh
are in same folder,
a include b with . ./b.sh
to include.
例如,a.sh
和b.sh
在同一个文件夹中,a 包含 b 与 . ./b.sh
包含。
When run script out of the folder, for example with xx/xx/xx/a.sh
, file b.sh
will not found: ./b.sh: No such file or directory
.
当在文件夹外运行脚本时,例如使用xx/xx/xx/a.sh
,b.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.sh
from 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.sh
directly. The content of color.sh
is as follows.
不知道为什么,./
而不是color.sh
直接。内容color.sh
如下。
Making use of File color.sh
does not error but, the color do not display. I have tested this in Ubuntu 18.04
and the Bash
version is:
使用File color.sh
不报错,颜色不显示。我已经测试过了Ubuntu 18.04
,Bash
版本是:
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)