通常包含脚本的方式是"source"

eg:

main.sh:

#!/bin/bash

source incl.sh

echo "The main script"

incl.sh:

echo "The included script"

执行“。/main.sh”的结果是:

The included script
The main script

... 现在,如果您试图从另一个位置执行该shell脚本,它将无法找到包含,除非它在您的路径中。

确保脚本能够找到包含脚本的好方法是什么,特别是在脚本需要可移植的情况下?


当前回答

我倾向于让我的脚本彼此相对。 这样我就可以使用dirname:

#!/bin/sh

my_dir="$(dirname "$0")"

"$my_dir/other_script.sh"

其他回答

根据我的说法,脚本包含的合适位置是/usr/local/lib/

/usr/local/lib 与本地安装程序相关联的文件。

我个人更喜欢/usr/local/lib/bash/includes。 有bash-helper库用于以这种方式包含库:

#!/bin/bash

. /usr/local/lib/bash/includes/bash-helpers.sh

include api-client || exit 1                   # include shared functions
include mysql-status/query-builder || exit 1   # include script functions

# include script functions with status message
include mysql-status/process-checker; status 'process-checker' $? || exit 1
include mysql-status/nonexists; status 'nonexists' $? || exit 1

我知道我迟到了,但这应该工作,无论你如何开始脚本和使用内置专属:

DIR="${BASH_SOURCE%/*}"
if [[ ! -d "$DIR" ]]; then DIR="$PWD"; fi
. "$DIR/incl.sh"
. "$DIR/main.sh"

. (dot)命令是source的别名,$PWD是工作目录的路径,BASH_SOURCE是一个数组变量,其成员是源文件名,${string%substring}从$string后面删除$substring的最短匹配

我倾向于让我的脚本彼此相对。 这样我就可以使用dirname:

#!/bin/sh

my_dir="$(dirname "$0")"

"$my_dir/other_script.sh"

我在这里看到的大多数答案似乎都把事情复杂化了。这个方法对我来说一直很有效:

FULLPATH=$(readlink -f $0)
INCPATH=${FULLPATH%/*}

INCPATH将保存脚本的完整路径,不包括脚本文件名,无论脚本是如何调用的(通过$ path,相对或绝对)。

在此之后,只需要在同一目录中包含文件即可:

. $INCPATH/file_to_include.sh

参考:TecPorto /位置独立包括

这应该可靠地工作:

source_relative() {
 local dir="${BASH_SOURCE%/*}"
 [[ -z "$dir" ]] && dir="$PWD"
 source "$dir/$1"
}

source_relative incl.sh