如何在bashrc中引用相对路径的脚本文件

3

我有多个bash文件。 我想写一个主bash文件,该文件将包括当前目录中所有所需的bash文件。 我尝试像这样:

#!/bin/bash
HELPER_DIR=`dirname $0`
.$HELPER_DIR/alias

但是,当我将以下行放入我的 $HOME/.bashrc 文件中时:
if [ -f /home/vivek/Helpers/bash/main.bash ]; then
    . /home/vivek/Helpers/bash/main.bash
fi

我遇到了错误“没有这个文件 ./alias”,但是文件 alias 是存在的。我该如何包含相对路径下的 bash 文件?
3个回答

3

请使用$( dirname "${BASH_SOURCE[0]}" )代替。

我在~/.bashrc中添加了以下两行:

echo '$0=' $0
echo '$BASH_SOURCE[0]=' ${BASH_SOURCE[0]}

并启动了 Bash:

$ bash
$0= bash
$BASH_SOURCE[0]= /home/igor/.bashrc

当您使用source(或.)启动脚本或在~/.bashrc中使用时,$0和$BASH_SOURCE之间存在差异。

1

$( dirname "${BASH_SOURCE[0]}" )如果你从相同的目录调用脚本,则返回 . ,如果你使用相对路径调用它,例如../myscript.sh,则返回相对路径。

我使用script_dir=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )来获取脚本所在的目录。

这是一个测试此功能的示例脚本:

#!/bin/bash
# This script is located at /home/lrobert/test.sh

# This just tests the current PWD
echo "PWD: $(pwd)"


# Using just bash source returns the relative path to the script
# If called from /home with the command 'lrobert/test.sh' this returns 'lrobert'
bash_source="$(dirname "${BASH_SOURCE[0]}")"
echo "bash_source: ${bash_source}"


# This returns the actual path to the script
# Returns /home/lrobert when called from any directory
script_dir=$( cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
echo "script_dir: ${script_dir}"

# This just tests to see if our PWD was modified
echo "PWD: $(pwd)"

1

在“点”后面需要留一个空格。

. $HELPER_DIR/alias

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接