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

时间:2021-12-30 13:57:00

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文件来运行包含在简单调用函数名中的函数。

3 个解决方案

#1


132  

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.

#2


26  

Yes, use source or the short form which is just .:

是的,使用来源或简短的形式。

. other_script.sh

#3


13  

Above answers is 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.

例如,一个。sh和b。sh在同一个文件夹中,a包含b和。/b。包括上海。

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。不会发现:./b。sh:没有这样的文件或目录。

I use

我使用

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

#1


132  

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.

#2


26  

Yes, use source or the short form which is just .:

是的,使用来源或简短的形式。

. other_script.sh

#3


13  

Above answers is 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.

例如,一个。sh和b。sh在同一个文件夹中,a包含b和。/b。包括上海。

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。不会发现:./b。sh:没有这样的文件或目录。

I use

我使用

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