通常包含脚本的方式是"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脚本,它将无法找到包含,除非它在您的路径中。

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


当前回答

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

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的最短匹配

其他回答

即使脚本是原始的,这也是有效的:

source "$( dirname "${BASH_SOURCE[0]}" )/incl.sh"

如果在同一个目录下,你可以使用dirname $0:

#!/bin/bash

source $(dirname $0)/incl.sh

echo "The main script"

替代:

scriptPath=$(dirname $0)

is:

scriptPath=${0%/*}

. .优点是不依赖于dirname,这不是一个内置命令(在模拟器中并不总是可用)。

这是一个很好的函数。它建立在@sacii所做的基础上。谢谢你!

它将允许您列出任意数量的空格分隔的脚本名称到source(相对于调用source_files的脚本)。

可选的是,你可以传递一个绝对路径或相对路径作为第一个参数,它将从那里来源。

您可以多次调用它(参见下面的示例)以从不同的dirs中获取脚本

#!/usr/bin/env bash

function source_files() {
  local scripts_dir
  scripts_dir="$1"

  if [ -d "$scripts_dir" ]; then
    shift
  else
    scripts_dir="${BASH_SOURCE%/*}"
    if [[ ! -d "$scripts_dir" ]]; then scripts_dir="$PWD"; fi
  fi

  for script_name in "$@"; do
    # shellcheck disable=SC1091 disable=SC1090
    . "$scripts_dir/$script_name.sh"
  done
}

下面是一个示例,您可以运行来展示如何使用它

#!/usr/bin/env bash

function source_files() {
  local scripts_dir
  scripts_dir="$1"

  if [ -d "$scripts_dir" ]; then
    shift
  else
    scripts_dir="${BASH_SOURCE%/*}"
    if [[ ! -d "$scripts_dir" ]]; then scripts_dir="$PWD"; fi
  fi

  for script_name in "$@"; do
    # shellcheck disable=SC1091 disable=SC1090
    . "$scripts_dir/$script_name.sh"
  done
}

## -- EXAMPLE -- ##
# assumes dir structure:
# /
#   source_files.sh
#   sibling.sh
#   scripts/
#     child.sh
#   nested/
#     scripts/
#       grandchild.sh

cd /tmp || exit 1

# sibling.sh
tee sibling.sh <<- EOF > /dev/null 
  #!/usr/bin/env bash
  
  export SIBLING_VAR='sibling var value'
EOF

# scripts/child.sh
mkdir -p scripts
tee scripts/child.sh <<- EOF > /dev/null
  #!/usr/bin/env bash

  export CHILD_VAR='child var value'
EOF

# nested/scripts/grandchild.sh
mkdir -p nested/scripts
tee nested/scripts/grandchild.sh <<- EOF > /dev/null
  #!/usr/bin/env bash

  export GRANDCHILD_VAR='grandchild var value'
EOF

source_files 'sibling'
source_files 'scripts' 'child'
source_files 'nested/scripts' 'grandchild'

echo "$SIBLING_VAR"
echo "$CHILD_VAR"
echo "$GRANDCHILD_VAR"

rm sibling.sh
rm -rf scripts nested

cd - || exit 1

打印:

sibling var value
child var value
grandchild var value

Steve的回答绝对是正确的技术,但它应该被重构,以便您的installpath变量在一个单独的环境脚本中,所有这些声明都是在该脚本中进行的。

然后,所有脚本都以该脚本为源,如果安装路径发生更改,则只需在一个位置更改它。让事情更,呃,不受未来影响。天啊,我讨厌这个词!(-):

顺便说一句,当你以你的例子中所示的方式使用它时,你应该使用${installpath}引用变量:

. ${installpath}/incl.sh

如果省略大括号,一些shell将尝试展开变量“installpath/ include .sh”!