问题
当前接受的答案仅在重要条件下有效。鉴于...
/foo/bar/first.sh:
function func1 {
echo "Hello $1"
}
和
/foo/bar/second.sh:
#!/bin/bash
source ./first.sh
func1 World
仅当first.sh从位于所在目录的同一目录中执行时,此方法才有效first.sh。就是 如果shell当前的工作路径是/foo,则尝试运行命令
cd /foo
./bar/second.sh
打印错误:
/foo/bar/second.sh: line 4: func1: command not found
这是因为source ./first.sh相对于当前的工作路径,而不是脚本的路径。因此,一种解决方案可能是利用subshell并运行
(cd /foo/bar; ./second.sh)
更通用的解决方案
鉴于...
/foo/bar/first.sh:
function func1 {
echo "Hello $1"
}
和
/foo/bar/second.sh:
#!/bin/bash
source $(dirname "$0")/first.sh
func1 World
然后
cd /foo
./bar/second.sh
版画
Hello World
这个怎么运作
$0 返回执行脚本的相对或绝对路径
dirname 返回目录的相对路径,其中$ 0脚本存在
$( dirname "$0" )该dirname "$0"命令返回到已执行脚本目录的相对路径,该路径随后用作source命令的参数
- 在“ second.sh”中,
/first.sh只需追加导入的shell脚本的名称
source 将指定文件的内容加载到当前shell中