3

I have multiple bash file. I want to write a master bash file which will include all required bash file in current directory. I tried like this

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

But I when I put following line in my $HOME/.bashrc

if [ -f /home/vivek/Helpers/bash/main.bash ]; then
    . /home/vivek/Helpers/bash/main.bash
fi

I am getting error no such file ./alias. File alias is there. How can I include relative bash file ?

3 Answers 3

3

Use $( dirname "${BASH_SOURCE[0]}" ) instead.

I added these two lines two my ~/.bashrc:

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

and started bash:

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

There is a difference between $0 and $BASH_SOURCE when you start a script with source (or .) or in ~/.bashrc.

Sign up to request clarification or add additional context in comments.

Comments

1

You need to leave a space after the "dot"

. $HELPER_DIR/alias

Comments

1

$( dirname "${BASH_SOURCE[0]}" ) returns . if you invoke the script from the same directory or a relative path if you call it using a relative path such as ../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)"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.