2012-07-26 22 views
2

我有多個bash文件。 我想寫一個主bash文件,它將在當前目錄中包含所有必需的bash文件。 我試過這樣如何包含相對腳本源文件bashrc

#!/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文件?

回答

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 

有$ 0 $ BASH_SOURCE之間的差異,當你啓動一個腳本source(或. )或在~/.bashrc

1

您需要的「點」

. $HELPER_DIR/alias 
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)" 
相關問題