13

So I have one bash script which calls another bash script. The second script is in a different folder.

script1.sh:
"some_other_folder/script2.sh"
# do something

script2.sh:
src=$(pwd) # THIS returns current directory of script1.sh...
# do something

In this second script it has the line src=$(pwd) and since I'm calling that script from another script in a different directory, the $(pwd) returns the current directory of the first script.

Is there any way to get the current directory of the second script using a simple command within that script without having to pass a parameter?

Thanks.

jww
  • 97,681
  • 90
  • 411
  • 885
Travv92
  • 791
  • 4
  • 14
  • 27
  • This is a SO FAQ: [Can a Bash script tell what directory it's stored in?](http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in) – devnull May 31 '13 at 06:16
  • One comment on terminology. Current working directory refers to the single runtime value for each process - the directory in which it is running (i.e. answering the question, where is "."). A better way to ask the question is, "how do I locate the directory from which the second script is being executed". – ash Aug 22 '13 at 19:14
  • See also http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in?rq=1. – ash Aug 22 '13 at 19:14

2 Answers2

5

I believe you are looking for ${BASH_SOURCE[0]}, readlinkand dirname (though you can use bash string substitution to avoid dirname)

[jaypal:~/Temp] cat b.sh
#!/bin/bash

./tp/a.sh

[jaypal:~/Temp] pwd
/Volumes/Data/jaypalsingh/Temp

[jaypal:~/Temp] cat tp/a.sh
#!/bin/bash

src=$(pwd)
src2=$( dirname $( readlink -f ${BASH_SOURCE[0]} ) )
echo "$src"
echo "$src2"

[jaypal:~/Temp] ./b.sh
/Volumes/Data/jaypalsingh/Temp
/Volumes/Data/jaypalsingh/Temp/tp/
jaypal singh
  • 74,723
  • 23
  • 102
  • 147
4

Please try this to see if it helps

loc=`dirname $BASH_SOURCE`
Jijo Mathew
  • 222
  • 1
  • 3
  • 9