bash 被另一个bash脚本调用后获取文件的当前目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16850029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get current directory of file after getting called by another bash script
提问by Travv92
So I have one bash script which calls another bash script. The second script is in a different folder.
所以我有一个 bash 脚本,它调用另一个 bash 脚本。第二个脚本位于不同的文件夹中。
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.
在第二个脚本中,它有一行src=$(pwd),因为我从不同目录中的另一个脚本调用该脚本,所以$(pwd)返回第一个脚本的当前目录。
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.
谢谢。
采纳答案by Jijo Mathew
Please try this to see if it helps
请试试这个,看看它是否有帮助
loc=`dirname $BASH_SOURCE`
回答by jaypal singh
I believe you are looking for ${BASH_SOURCE[0]}, readlinkand dirname(though you can use bash string substitution to avoid dirname)
我相信您正在寻找${BASH_SOURCE[0]},readlink和dirname(尽管您可以使用 bash 字符串替换来避免 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/

