Bash get current file directory after calling another Bash script

So I have one bash script that 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 call it a script from another script in another directory, $(pwd) returns the current directory of the first script.

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

Thanks.

+4
source share
2 answers

Try this to see if it helps.

 loc=`dirname $BASH_SOURCE` 
+3
source

I believe you are looking for ${BASH_SOURCE[0]} , readlink and dirname (although you can use bash string replacement 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/ 
+1
source

Source: https://habr.com/ru/post/1483715/


All Articles