如何使用其所在目录的工作目录执行任意脚本?

时间:2011-09-09 15:25:20

标签: linux bash groovy

我需要从bash执行一个groovy脚本文件,我需要脚本有一个它所在目录的工作目录。

也就是说,在我的bash脚本中,我这样做:

/opt/script/myscript.groovy &

但这似乎将工作目录设置为/etc/init.d,即我正在调用的目录。如何将该脚本的工作目录更改为/opt/script

4 个答案:

答案 0 :(得分:17)

如果您在/etc/init.d脚本中使用start-stop-daemon,则可以利用-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.

答案 1 :(得分:9)

  

/etc/init.d

可能你从/etc/init.d

那个runnig(启动)脚本

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

OR

...保持动态,添加: cd "$(dirname "$0")"

答案 2 :(得分: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的实际路径(规范化绝对路径名)。

答案 3 :(得分:1)

这样的事情可能是:

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