2

我有多个 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。文件别名在那里。如何包含相对 bash 文件?

4

3 回答 3

2

改为使用$( 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当您使用(or .) 或 in启动脚本时,$0 和 $BASH_SOURCE 之间存在差异~/.bashrc

于 2012-07-26T18:46:48.843 回答
1

您需要在“点”之后留一个空格

. $HELPER_DIR/alias
于 2012-07-26T18:48:39.447 回答
1

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

I use script_dir=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) to get the directory that the script is in.

Here's an example script to test this functionality:

#!/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)"
于 2015-02-03T20:19:38.073 回答