8

I need to execute a groovy script file from bash, and I need the script to have a working directory of the directory it exists in.

That is, in my bash script, I'm doing this:

/opt/script/myscript.groovy &

But this seems to set the working directory to /etc/init.d, the directory I'm calling from. How do I change the working directory for that script to /opt/script?

Stefan Kendall
  • 61,898
  • 63
  • 233
  • 391
  • The answer is here in some form or another: http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in – Chris Sep 09 '11 at 15:28
  • @Chris: Except it's not. Arbitrary script implies *not bash*. Bash specific answers will be downvoted. – Stefan Kendall Sep 09 '11 at 17:24

4 Answers4

18

If you are using start-stop-daemon inside your /etc/init.d script, you can take advantage of the -d parameter for achieving this:

   -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.
9

/etc/init.d

probably you are runnig (starting) that script from /etc/init.d?

Add cd /opt/script at the first line of the script

OR

...to keep it dynamic, add: cd "$(dirname "$0")"

The Bndr
  • 12,480
  • 16
  • 55
  • 97
2

In bash putting that in the script works best:

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

This will succeed even with the following invocation (of /path/to/script.sh):

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

where HERE=$(dirname $0) would fail.

Optionally you could also use pwd -P instead of just pwd, then $HERE will contain the realpath (canonicalized absolute pathname) as of man 3 realpath.

Johannes Weiss
  • 47,880
  • 15
  • 95
  • 129
1

Something like this maybe:

SCRIPT=/opt/script/myscript.groovy
pushd `dirname $SCRIPT`
./`basename $SCRIPT`
popd
Šimon Tóth
  • 33,420
  • 18
  • 94
  • 135
  • 1
    The `popd` isn't necessary in any environment except a DOS .BAT file; what a process does to change directory cannot affect the directory of the program that runs it. – Jonathan Leffler Sep 09 '11 at 16:12