简体   繁体   English

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

[英]How to include file in a bash shell script

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 文件一起使用,以便通过调用函数名称来运行其中包含的函数。

Simply put inside your script :只需放入您的脚本中:

source FILE

Or要么

. FILE # POSIX compliant

$ 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.

Above answers are correct, but if you run script in another folder, there will be some problem.以上答案是正确的,但是如果您在另一个文件夹中运行脚本,则会出现一些问题。

For example, a.sh and b.sh are in same folder, a use . ./b.sh例如, a.shb.sh都在同一个文件夹,一个使用. ./b.sh . ./b.sh to include b. . ./b.sh包括 b。

When you run script out of the folder, for example, 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./b.sh: No such file or directory

So I use所以我用

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

Yes, use source or the short form which is just .是的,使用源代码或只是. :

. other_script.sh

Syntax is source <file-name>语法是source <file-name>

ex.前任。 source config.sh

script - config.sh脚本 - config.sh

USERNAME="satish"
EMAIL="satish@linuxconcept.com"

calling script -调用脚本 -

#!/bin/bash
source config.sh
echo Welcome ${USERNAME}!
echo Your email is ${EMAIL}.

You can learn to include a bash script in another bash script here .您可以在此处学习在另一个 bash 脚本中包含一个 bash 脚本

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 ,我必须执行以下操作。

. ./color.sh

Not sure why the ./ and not color.sh directly.不知道为什么./而不是color.sh直接。 The content of color.sh is as follows. color.sh的内容如下。

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

Making use of File color.sh does not error but, the color do not display.使用File color.sh没有错误,但是颜色不显示。 I have tested this in Ubuntu 18.04 and the Bash version is:我在Ubuntu 18.04对此进行了测试, Bash版本是:

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

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

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