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

Mec*_*ash 102 linux bash include

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

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

Gil*_*not 168

只需放入脚本:

source FILE
Run Code Online (Sandbox Code Playgroud)

要么

. FILE
Run Code Online (Sandbox Code Playgroud)

这是同一件事.

$ 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.
Run Code Online (Sandbox Code Playgroud)

  • 注意 .是POSIX兼容而源不是 (16认同)
  • 不要混淆`.script.sh`与`./ script.sh`.我花了很多时间试图找出发生了什么 (8认同)
  • 我们可以考虑`. other.sh` 相当于将其他脚本复制并粘贴到父脚本中,或者是否有任何细微的差异? (2认同)

Fan*_*ung 38

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

例如,a.shb.sh在同一文件夹中,包括b . ./b.sh包含.

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

我用

. $(dirname "$0")/b.sh
Run Code Online (Sandbox Code Playgroud)


Pau*_*aul 32

是的,使用或简短形式,它只是.:

. other_script.sh
Run Code Online (Sandbox Code Playgroud)

  • 注意`.`版本可以在`sh`以及Bash上使用。“源”仅在Bash中有效。 (2认同)

小智 5

语法是 source <file-name>

前任。 source config.sh

脚本 - config.sh

USERNAME="satish"
EMAIL="satish@linuxconcept.com"
Run Code Online (Sandbox Code Playgroud)

调用脚本 -

#!/bin/bash
source config.sh
echo Welcome ${USERNAME}!
echo Your email is ${EMAIL}.
Run Code Online (Sandbox Code Playgroud)

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