Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I execute an arbitrary script with a working directory of the directory its in?

Tags:

linux

bash

groovy

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?

like image 628
Stefan Kendall Avatar asked Sep 09 '11 15:09

Stefan Kendall


People also ask

How do I run a script in another directory?

Using the pushd Command In the above script, we've used pushd and popd commands to switch between the directories. As we know, pushd saves the current directory and switches to the new directory given as an argument. And later, we can use popd to restore the pushed directory.

What is working directory in shell script?

The shell always identifies a particular directory within which you are assumed to be working. This directory is known as the working directory (also known as the current working directory). To work with a file within your working directory, you need specify only the file name with a command.

How do I navigate to a directory in shell script?

To change directories, use the command cd followed by the name of the directory (e.g. cd downloads ). Then, you can print your current working directory again to check the new path.


2 Answers

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.
like image 105
David Santiago Turiño Avatar answered Oct 25 '22 17:10

David Santiago Turiño


/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")"

like image 29
The Bndr Avatar answered Oct 25 '22 15:10

The Bndr