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
?
/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")"
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.
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
.
Something like this maybe:
SCRIPT=/opt/script/myscript.groovy
pushd `dirname $SCRIPT`
./`basename $SCRIPT`
popd