有没有办法在 shell 脚本中包含另一个 shell 脚本以便能够访问它的功能?
就像在 PHP 中一样,您可以将include
指令与其他 PHP 文件一起使用,以便通过调用函数名称来运行其中包含的函数。
只需放入您的脚本中:
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.
以上答案是正确的,但是如果您在另一个文件夹中运行脚本,则会出现一些问题。
例如,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
是的,使用source或简称.
:
. other_script.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}.
在我的情况下,为了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)