Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Source bash script to another one [duplicate]

Tags:

bash

shell

Possible Duplicate:
Reliable way for a bash script to get the full path to itself?

I have bash script test.sh which use functions from another search.sh script by following lines:

source ../scripts/search.sh
<call some functions from search.sh>

Both scripts are located in git repository. search.sh in <git_root>/scripts/ directory, test.sh is located in the same directory (but, generally speaking, could be located anywhere inside <git_root> directory - I mean I can't rely on the following source search.sh approach ).

When I call test.sh script from <git_root>/scripts/ everything works well, but as soon as I change current working directory test.sh fails:

cd <git_root>/scripts/
./test.sh         //OK
cd ..
./scripts/test.sh //FAILS
./scripts/test.sh: line 1: ../scripts/search.sh: No file or directory ...

Thus what I have:

  1. Relative path of search.sh script towards <git_root> directory

What I want: To have ability to run test.sh from anywhere inside <git_root> without errors.

P.S.: It is not possible to use permanent absolute path to search.sh as git repository can be cloned to any location.

like image 926
likern Avatar asked Jan 09 '13 14:01

likern


1 Answers

If both the scripts are in the same directory, then if you get the directory that the running script is in, you use that as the directory to call the other script:

# Get the directory this script is in
pushd `dirname $0` > /dev/null
SCRIPTPATH=`pwd -P`
popd > /dev/null

# Now use that directory to call the other script
source $SCRIPTPATH/search.sh

Taken from the accepted answer of the question I marked this question a duplicatre of: https://stackoverflow.com/a/4774063/440558

like image 118
Some programmer dude Avatar answered Oct 01 '22 03:10

Some programmer dude