【问题标题】:How to include file in a bash shell script如何在 bash shell 脚本中包含文件
【发布时间】:2012-06-05 02:55:46
【问题描述】:

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

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

【问题讨论】:

标签: linux bash include


【解决方案1】:

只需放入您的脚本中:

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.

【讨论】:

  • 请注意 .符合 POSIX,而源代码不符合
  • 但是这里的源代码与我们在C 语言中所做的包含并不完全相同。这里 source 正在将子脚本执行到主脚本中。如果我只想从子脚本中调用特定函数怎么办?
  • 不要将. script.sh./script.sh 混淆。我花了几个小时试图弄清楚发生了什么
  • 而 .是 POSIX 兼容的,这意味着它可以在 sh、dash、zsh 和其他 POSIX shell 上工作。最好使用 .因为有些 shell 有自己的、相似但有点不同的“源”版本,这可能会破坏您的应用程序。
  • 我们是否可以认为. other.sh 相当于将其他脚本复制并粘贴到父脚本中,还是有任何细微差别?
【解决方案2】:

是的,使用source 或简写形式,即.

. other_script.sh

【讨论】:

  • 请注意 . 版本适用于 sh 以及 Bash。 “源代码”仅适用于 Bash。
【解决方案3】:

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

例如,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

【讨论】:

  • 这仅适用于一级源/包含。如果b.sh 进一步包含使用. $(dirname "$0")/c.shc.sh,那么它将惨遭失败,因为在采购/包括b 时,$0 是shell 本身,并且到目前为止我不知道有任何方法可以找出目录b.sh
【解决方案4】:

在我的情况下,为了在init.sh 中包含同一目录中的color.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)

【讨论】:

  • 这只会为您提供当前工作目录中的文件,而不是 init.sh 所在的目录(如果您首先使用 ./init.sh 启动它,则它们一致)。
【解决方案5】:

语法是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}.

你可以学习include a bash script in another bash script here

【讨论】:

    猜你喜欢
    • 2013-07-05
    • 2018-02-24
    • 1970-01-01
    • 2011-09-04
    • 1970-01-01
    • 1970-01-01
    • 2015-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多