2011-09-09 36 views
7

我需要執行從慶典Groovy腳本文件,我需要的腳本,有它存在於目錄的工作目錄如何執行一個任意腳本與目錄的工作目錄?

也就是說,在我的bash腳本,我這樣做:

/opt/script/myscript.groovy & 

但是,這似乎將工作目錄設置爲/etc/init.d,我打電話給的目錄。如何將該腳本的工作目錄更改爲/opt/script

+0

答案就在這裏以某種形式另:http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in – Chris

+0

@Chris:除非不是。任意腳本意味着*不是bash *。 Bash具體答案將被降低。 –

回答

7

/etc/init.d

可能是你運行過程中出現(起點),從/etc/init.d腳本?

在腳本的第一行添加cd /opt/script

OR

...保持它的動態,添加: cd "$(dirname "$0")"

+0

夠簡單。在腳本的其餘部分工作正常之前CD'ing。 –

1

事情是這樣的,也許:

SCRIPT=/opt/script/myscript.groovy 
pushd `dirname $SCRIPT` 
./`basename $SCRIPT` 
popd 
+1

除了DOS .BAT文件外,'popd'在任何環境中都不是必需的;一個進程如何改變目錄不會影響運行它的程序的目錄。 –

2

bash把這個腳本放在最好的作品中:

HERE=$(cd -- $(dirname ${BASH_SOURCE[0]}) > /dev/null && pwd) 
cd -- "$HERE" 

這甚至會與下面的調用(的/path/to/script.sh)成功:

PATH="/path/to:$PATH" bash script.sh 

其中HERE=$(dirname $0)會失敗。

可選,你也可以使用pwd -P,而不是僅僅pwd,然後$HERE將包含真實路徑(規範化的絕對​​路徑名)作爲man 3 realpath

15

如果您正在使用的/etc/init.d腳本中的啓動停止守護進程,你可以利用-d參數爲實現這一目標:

-d, --chdir path 
      Chdir to path before starting the process. This is done after the chroot if the -r|--chroot option is set. When not specified, start-stop-daemon will chdir to the root directory before starting the process. 
相關問題