I've searched through the forum for a solution to this problem, but I haven't found anything. I have 2 script files that are in different directories.
My first script, let's call it "/one/two/a.sh" looks like this:
#!/bin/sh
IN_DIR=`dirname $0`
CUR_DIR=`pwd`
cd $IN_DIR
A_DIR=`pwd`
cd $CUR_DIR
export $A_DIR
echo $A_DIR
Running that, gives me "/one/two/", and A_DIR is set to that value.
Now I have a second script in a different directory that sources this script. Let's call it "/hello/bye/b.sh"
#!/bin/sh
. /one/two/a.sh
echo $A_DIR
In this case, I DO NOT get "/one/two/", but instead: "/hello/bye/"
I guess this is because the $0 variable inside the first script becomes "b.sh" instead. I want the first script to always source the $A_DIR variable with the path of the script, and I do not want to rely on hard-coding it, nor using the "find" command.
Does anyone have any ideas? Any help would be great!
I make some change directory calls inside a.sh, so that the pwd becomes dirname ${0}. The problem I think is that, I'm not invoking a.sh, but sourcing it inside b.sh:
#!/bin/sh
. /one/two/a.sh
echo $A_DIR
Let's say I invoke b.sh with the following:
/hello/bye/b.sh
Because a.sh makes the following call: dirname ${0}. It gets the path of the current value inside $0, which is actually "/hello/bye/b.sh", since that script is the one being actually invoked.
On the same lines of your last post, just a few recommendations...
Yes, that's the problem, you need to invoke a.sh script. Sourcing it, will cause it to get executed in the place of the current shell ( b.sh shell/environment), so every command of a.sh will get place in the b.sh shell /environment.
Secondly, in your situation you don't need export in a.sh. That will export the value of the variable A_DIR in the subshells of a.sh ( ex. if you invoke other scripts within a.sh, etc ... ). So to access the value of A_DIR in the outer script b.sh for further processing, one way of doing it, is through invoking a.sh and put the value of A_DIR in a temporary file inside a.sh :
a.sh script :
#!/bin/sh
IN_DIR=`dirname $0`
CUR_DIR=`pwd`
cd $IN_DIR
A_DIR=`pwd`
cd $CUR_DIR
echo $A_DIR > /hello/by/temp_file
and b.sh script :
#!/bin/sh
/one/two/a.sh
my_dir=`cat /hello/by/temp_file`
#To see the result
echo " This is A_DIR " $my_dir
# If you don't need the temp_file
rm /hello/by/temp_file