【发布时间】:2012-06-05 02:55:46
【问题描述】:
有没有办法在 shell 脚本中包含另一个 shell 脚本以便能够访问其功能?
就像在 PHP 中一样,您可以将 include 指令与其他 PHP 文件一起使用,以便通过调用函数名称来运行其中包含的函数。
【问题讨论】:
-
@Troubadour 感谢您的参考。尽管帖子引用了
source命令,但问题本身就是询问如何查明source文件的位置。
有没有办法在 shell 脚本中包含另一个 shell 脚本以便能够访问其功能?
就像在 PHP 中一样,您可以将 include 指令与其他 PHP 文件一起使用,以便通过调用函数名称来运行其中包含的函数。
【问题讨论】:
source 命令,但问题本身就是询问如何查明source 文件的位置。
只需放入您的脚本中:
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.
【讨论】:
C 语言中所做的包含并不完全相同。这里 source 正在将子脚本执行到主脚本中。如果我只想从子脚本中调用特定函数怎么办?
. script.sh 与./script.sh 混淆。我花了几个小时试图弄清楚发生了什么
. other.sh 相当于将其他脚本复制并粘贴到父脚本中,还是有任何细微差别?
是的,使用source 或简写形式,即.:
. other_script.sh
【讨论】:
. 版本适用于 sh 以及 Bash。 “源代码”仅适用于 Bash。
上面的答案都是正确的,但是如果你在另一个文件夹中运行脚本,就会出现一些问题。
例如,a.sh 和 b.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.sh 的c.sh,那么它将惨遭失败,因为在采购/包括b 时,$0 是shell 本身,并且到目前为止我不知道有任何方法可以找出目录b.sh
在我的情况下,为了在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 启动它,则它们一致)。
语法是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}.
【讨论】: