155

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

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

4

5 回答 5

233

只需放入您的脚本中:

source FILE

或者

. 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.
于 2012-05-30T20:20:14.467 回答
71

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

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

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

所以我用

. $(dirname "$0")/b.sh
于 2016-12-22T09:50:50.597 回答
34

是的,使用source或简称.

. other_script.sh
于 2012-05-30T20:20:29.863 回答
8

语法是source <file-name>

前任。source config.sh

脚本 - config.sh

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

调用脚本 -

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

您可以在此处学习在另一个 bash 脚本中包含一个 bash 脚本

于 2020-08-05T05:27:38.930 回答
3

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

. ./color.sh

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

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

使用File color.sh不出错但颜色不显示。我已经对此进行Ubuntu 18.04了测试,Bash版本是:

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

于 2018-10-01T02:21:13.070 回答