Get current directory of file after getting called by another bash script [duplicate]

大兔子大兔子 提交于 2019-12-01 15:19:27

问题


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.


回答1:


Please try this to see if it helps

loc=`dirname $BASH_SOURCE`



回答2:


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/


来源:https://stackoverflow.com/questions/16850029/get-current-directory-of-file-after-getting-called-by-another-bash-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!