2013-05-31 50 views
4

所以我有一个bash脚本调用另一个bash脚本。 第二个脚本位于不同的文件夹中。Bash获得另一个bash脚本调用后的文件当前目录

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

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

在它的线src=$(pwd)既然我打电话从另一个脚本,脚本在不同的目录中第二个剧本,$(pwd)返回第一个脚本的当前目录。

有没有什么办法可以在该脚本中使用简单的命令获取第二个脚本的当前目录,而无需传递参数?

谢谢。

+0

这是一个SO常见问题解答:[Bash脚本可以告诉它存储在哪个目录?](http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in) – devnull

+0

对术语的一种评论。当前工作目录是指每个进程的单个运行时值 - 它运行的目录(即回答问题,其中是“。”)。问一个问题的更好的方法是,“我如何找到第二个脚本正在执行的目录”。 – ash

+0

参见http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in?rq=1。 – ash

回答

3

请试试这个,看看它是否有助于

loc=`dirname $BASH_SOURCE` 
+0

谢谢,这工作! – Travv92

1

我相信你正在寻找${BASH_SOURCE[0]}readlinkdirname(虽然你可以使用bash字符串替换,以避免目录名)

[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/ 
相关问题